<?php
// cPanel path: /home/jewellersbd/public_html/erp.jewellersbd.com/api/purchases/get_purchases.php

require_once __DIR__ . '/../../api/_core.php';
require_once __DIR__ . '/../../config/db.php';

header('Content-Type: application/json');

try {
    $date_from = $_GET['date_from'] ?? date('Y-m-01');
    $date_to   = $_GET['date_to']   ?? date('Y-m-d');

    // ── Summary ────────────────────────────────────────────────────────
    $sumQ = $pdo->prepare(
        "SELECT
            COUNT(*)              AS total_cnt,
            COALESCE(SUM(p.total_amount),0)  AS total_amount,
            COALESCE(SUM(p.paid_amount),0)   AS paid_amount,
            COALESCE(SUM(p.due_amount),0)    AS due_amount,
            COALESCE(SUM(p.gross_weight),0)  AS gross_weight,
            COALESCE(SUM(p.pure_weight),0)   AS pure_weight
         FROM purchases p
         WHERE p.purchase_date BETWEEN :df AND :dt
           AND p.deleted_at IS NULL"
    );
    $sumQ->execute([':df' => $date_from, ':dt' => $date_to]);
    $summary = $sumQ->fetch(PDO::FETCH_ASSOC);

    // ── List ───────────────────────────────────────────────────────────
    $listQ = $pdo->prepare(
        "SELECT
            p.id,
            p.purchase_date,
            p.karat,
            p.item_name,
            p.gross_weight,
            p.pure_weight,
            p.actual_purity,
            p.total_pieces,
            p.rate_per_vori_24k,
            p.total_amount,
            COALESCE(p.paid_amount, 0)    AS paid_amount,
            COALESCE(p.due_amount, 0)     AS due_amount,
            COALESCE(p.payment_status,'') AS payment_status,
            p.vori,
            p.ana,
            p.roti,
            p.point,
            p.note,
            COALESCE(pt.name,'') AS party_name
         FROM purchases p
         LEFT JOIN parties pt ON pt.id = p.party_id
         WHERE p.purchase_date BETWEEN :df AND :dt
           AND p.deleted_at IS NULL
         ORDER BY p.purchase_date DESC, p.id DESC"
    );
    $listQ->execute([':df' => $date_from, ':dt' => $date_to]);
    $list = $listQ->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success'  => true,
        'summary'  => $summary,
        'data'     => $list,
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}