<?php
require_once '../../config/db.php';
require_once '../../config/session.php';
require_once '../../config/response.php';

if (function_exists('session_start_if_not_started')) {
    session_start_if_not_started();
} else {
    if (session_status() === PHP_SESSION_NONE) session_start();
}

if (!is_logged_in()) {
    send_response(401, false, 'অনুমতি নেই');
}

// from/to এবং from_date/to_date — দুটোই সাপোর্ট করে
$from_date = $_GET['from_date'] ?? $_GET['from'] ?? date('Y-m-d');
$to_date   = $_GET['to_date']   ?? $_GET['to']   ?? date('Y-m-d');
$limit     = (int)($_GET['limit']  ?? 50);
$offset    = (int)($_GET['offset'] ?? 0);

try {
    $where  = "WHERE ps.purchase_date BETWEEN ? AND ?
               AND ps.deleted_at IS NULL";
    $params = [$from_date, $to_date];

    $countStmt = $pdo->prepare(
        "SELECT COUNT(*) as total
         FROM purchase_stock ps $where"
    );
    $countStmt->execute($params);
    $total = $countStmt->fetch()['total'];

    $sumStmt = $pdo->prepare(
        "SELECT
            COUNT(*)             AS total_entries,
            SUM(ps.gross_weight) AS total_gross,
            SUM(ps.pure_weight)  AS total_pure,
            SUM(ps.total_pieces) AS total_pieces,
            SUM(ps.total_amount) AS total_amount
         FROM purchase_stock ps $where"
    );
    $sumStmt->execute($params);
    $summary = $sumStmt->fetch();

    $dataParams   = $params;
    $dataParams[] = $limit;
    $dataParams[] = $offset;

    $stmt = $pdo->prepare(
        "SELECT
            ps.id,
            ps.purchase_date,
            ps.item_name,
            ps.karat,
            ps.gross_weight,
            ps.pure_weight,
            ps.total_pieces,
            ps.rate_per_vori,
            ps.total_amount,
            ps.note,
            ps.created_at,
            pt.name        AS party_name,
            pt.phone       AS party_phone,
            sl.name        AS location_name,
            pm.method_name AS payment_method
         FROM purchase_stock ps
         LEFT JOIN parties pt
            ON ps.party_id = pt.id
         LEFT JOIN stock_locations sl
            ON ps.location_id = sl.id
         LEFT JOIN payment_methods pm
            ON ps.payment_method_id = pm.id
         $where
         ORDER BY ps.id DESC
         LIMIT ? OFFSET ?"
    );
    $stmt->execute($dataParams);
    $purchases = $stmt->fetchAll();

    foreach ($purchases as &$p) {
        $bcStmt = $pdo->prepare(
            "SELECT
                COUNT(*) AS total,
                SUM(CASE WHEN status='in_stock'
                    THEN 1 ELSE 0 END) AS in_stock
             FROM barcode_stock
             WHERE purchase_stock_id = ?
             AND deleted_at IS NULL"
        );
        $bcStmt->execute([$p['id']]);
        $bc = $bcStmt->fetch();
        $p['barcode_count']  = (int)($bc['total']    ?? 0);
        $p['in_stock_count'] = (int)($bc['in_stock'] ?? 0);
    }
    unset($p);

    send_response(200, true, 'সফল', [
        'purchases' => $purchases,
        'total'     => (int)$total,
        'summary'   => [
            'total_entries' => (int)($summary['total_entries'] ?? 0),
            'total_gross'   => round($summary['total_gross']   ?? 0, 3),
            'total_pure'    => round($summary['total_pure']    ?? 0, 3),
            'total_pieces'  => (int)($summary['total_pieces']  ?? 0),
            'total_amount'  => round($summary['total_amount']  ?? 0, 2)
        ]
    ]);

} catch (Exception $e) {
    send_response(500, false, 'সার্ভার এরর: ' . $e->getMessage());
}
?>