<?php
/**
 * File: api/karigar/list_karigars.php
 * Purpose: Karigar list with pending gold + labor due (compact + detail)
 * Method : GET
 * Query  : ?search=<text>&filter=<all|pending|settled>&with_detail=0|1
 * Output : { success, message, data: { karigars: [...], summary: {...} } }
 * Date   : 2026-05-27
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

function out_json($code, $success, $message, $data = null) {
    http_response_code($code);
    echo json_encode([
        'success' => (bool)$success,
        'status'  => (bool)$success,
        'message' => $message,
        'data'    => $data
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (function_exists('is_logged_in') && !is_logged_in()) {
    out_json(401, false, 'লগইন প্রয়োজন', null);
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    out_json(500, false, 'Database connection পাওয়া যায়নি', null);
}

$search      = trim((string)($_GET['search'] ?? ''));
$filter      = trim((string)($_GET['filter'] ?? 'all'));
$with_detail = (int)($_GET['with_detail'] ?? 0);

try {
    // ===== Base query =====
    $where  = ["p.is_karigar = 1", "p.deleted_at IS NULL"];
    $params = [];

    if ($search !== '') {
        $where[]      = "(p.name LIKE :s1 OR p.phone LIKE :s2)";
        $params[':s1'] = '%' . $search . '%';
        $params[':s2'] = '%' . $search . '%';
    }

    $whereSql = implode(' AND ', $where);

    // ===== Main query =====
    // Pending pure gold = total issued pure - total received pure - wastage_accepted
    // Outstanding labor = total labor charged - total labor paid
    $sql = "
        SELECT
            p.id,
            p.name,
            p.phone,
            p.address,
            p.note,
            p.created_at,
            
            -- Compact essentials
            COALESCE((
                SELECT SUM(ki.pure_weight_gram)
                FROM karigar_issues ki
                WHERE ki.karigar_party_id = p.id AND ki.deleted_at IS NULL
            ), 0) AS total_issued_pure,
            
            COALESCE((
                SELECT SUM(kr.pure_weight_gram)
                FROM karigar_receives kr
                WHERE kr.karigar_party_id = p.id AND kr.deleted_at IS NULL
            ), 0) AS total_received_pure,
            
            COALESCE((
                SELECT SUM(kr.wastage_pure_gram)
                FROM karigar_receives kr
                WHERE kr.karigar_party_id = p.id AND kr.deleted_at IS NULL
            ), 0) AS total_wastage_pure,
            
            COALESCE((
                SELECT SUM(kr.labor_amount)
                FROM karigar_receives kr
                WHERE kr.karigar_party_id = p.id AND kr.deleted_at IS NULL
            ), 0) AS total_labor_charged,
            
            COALESCE((
                SELECT SUM(kl.cash_out)
                FROM karigar_ledger kl
                WHERE kl.karigar_party_id = p.id
                  AND kl.entry_type = 'LABOR_PAYMENT'
            ), 0) AS total_labor_paid,
            
            -- Heavy detail
            COALESCE((
                SELECT SUM(ki.gross_weight_gram)
                FROM karigar_issues ki
                WHERE ki.karigar_party_id = p.id AND ki.deleted_at IS NULL
            ), 0) AS total_issued_gross,
            
            COALESCE((
                SELECT SUM(kr.gross_weight_gram)
                FROM karigar_receives kr
                WHERE kr.karigar_party_id = p.id AND kr.deleted_at IS NULL
            ), 0) AS total_received_gross,
            
            COALESCE((
                SELECT COUNT(*)
                FROM karigar_issues ki
                WHERE ki.karigar_party_id = p.id AND ki.deleted_at IS NULL
            ), 0) AS total_issues,
            
            COALESCE((
                SELECT COUNT(*)
                FROM karigar_receives kr
                WHERE kr.karigar_party_id = p.id AND kr.deleted_at IS NULL
            ), 0) AS total_receives,
            
            COALESCE((
                SELECT MAX(ki.issue_date)
                FROM karigar_issues ki
                WHERE ki.karigar_party_id = p.id AND ki.deleted_at IS NULL
            ), NULL) AS last_issue_date
            
        FROM parties p
        WHERE $whereSql
        ORDER BY p.name ASC
    ";

    $stmt = $pdo->prepare($sql);
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // ===== Calculate derived fields + filter =====
    $karigars = [];
    $sum_pending = 0.0;
    $sum_labor_due = 0.0;

    foreach ($rows as $r) {
        $issued_pure   = (float)$r['total_issued_pure'];
        $received_pure = (float)$r['total_received_pure'];
        $wastage_pure  = (float)$r['total_wastage_pure'];
        $labor_charged = (float)$r['total_labor_charged'];
        $labor_paid    = (float)$r['total_labor_paid'];

        $pending_pure = $issued_pure - $received_pure - $wastage_pure;
        $labor_due    = $labor_charged - $labor_paid;

        // ===== Filter logic =====
        if ($filter === 'pending') {
            if ($pending_pure <= 0.001 && $labor_due <= 0.01) continue;
        } elseif ($filter === 'settled') {
            if ($pending_pure > 0.001 || $labor_due > 0.01) continue;
        }

        $card = [
            'id'                  => (int)$r['id'],
            'name'                => (string)$r['name'],
            'phone'               => (string)($r['phone'] ?? ''),
            'pending_pure_gram'   => round($pending_pure, 4),
            'labor_due'           => round($labor_due, 2),
            'last_issue_date'     => $r['last_issue_date'],
        ];

        if ($with_detail === 1) {
            $card['address']             = (string)($r['address'] ?? '');
            $card['note']                = (string)($r['note'] ?? '');
            $card['total_issued_gross']  = round((float)$r['total_issued_gross'], 4);
            $card['total_issued_pure']   = round($issued_pure, 4);
            $card['total_received_gross']= round((float)$r['total_received_gross'], 4);
            $card['total_received_pure'] = round($received_pure, 4);
            $card['total_wastage_pure']  = round($wastage_pure, 4);
            $card['total_labor_charged'] = round($labor_charged, 2);
            $card['total_labor_paid']    = round($labor_paid, 2);
            $card['total_issues']        = (int)$r['total_issues'];
            $card['total_receives']      = (int)$r['total_receives'];
        }

        $karigars[]    = $card;
        $sum_pending  += $pending_pure;
        $sum_labor_due += $labor_due;
    }

    $summary = [
        'total_karigars'        => count($karigars),
        'total_pending_pure'    => round($sum_pending, 4),
        'total_outstanding_due' => round($sum_labor_due, 2)
    ];

    out_json(200, true, 'OK', [
        'karigars' => $karigars,
        'summary'  => $summary
    ]);

} catch (Throwable $e) {
    out_json(500, false, 'সার্ভার ত্রুটি: ' . $e->getMessage(), null);
}
