<?php
/**
 * File: api/karigar/pending_issues.php
 * Purpose: একটি karigar এর pending issues (যেগুলোতে এখনো full receive আসেনি)
 *          Receive screen এর "Related Issue" dropdown এর জন্য
 * Method : GET
 * Query  : ?karigar_id=<int>&include_all=0|1
 * Output : { success, data: { issues: [...] } }
 */

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);
}

$karigar_id  = (int)($_GET['karigar_id'] ?? 0);
$include_all = (int)($_GET['include_all'] ?? 0);

if ($karigar_id <= 0) out_json(400, false, 'Karigar ID দিন', null);

try {
    // ===== Karigar এর সব issues =====
    $sql = "
        SELECT
            ki.id,
            ki.issue_date,
            ki.karat,
            ki.purity_percent,
            ki.gross_weight_gram,
            ki.pure_weight_gram,
            ki.pieces,
            ki.item_description,
            ki.source_type,
            ki.job_id,
            COALESCE((
                SELECT SUM(kr.pure_weight_gram)
                FROM karigar_receives kr
                WHERE kr.related_issue_id = ki.id AND kr.deleted_at IS NULL
            ), 0) AS received_pure,
            COALESCE((
                SELECT SUM(kr.wastage_pure_gram + kr.shortage_pure_gram)
                FROM karigar_receives kr
                WHERE kr.related_issue_id = ki.id AND kr.deleted_at IS NULL
            ), 0) AS adjusted_pure
        FROM karigar_issues ki
        WHERE ki.karigar_party_id = ?
          AND ki.deleted_at IS NULL
        ORDER BY ki.issue_date DESC, ki.id DESC
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([$karigar_id]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $issues = [];
    foreach ($rows as $r) {
        $issued_pure   = (float)$r['pure_weight_gram'];
        $received_pure = (float)$r['received_pure'];
        $adjusted_pure = (float)$r['adjusted_pure'];
        $balance_pure  = round($issued_pure - $received_pure - $adjusted_pure, 4);

        $is_pending = $balance_pure > 0.001;

        if (!$include_all && !$is_pending) continue;

        $issues[] = [
            'id'                => (int)$r['id'],
            'issue_date'        => $r['issue_date'],
            'karat'             => $r['karat'],
            'purity_percent'    => (float)$r['purity_percent'],
            'gross_weight_gram' => (float)$r['gross_weight_gram'],
            'pure_weight_gram'  => $issued_pure,
            'received_pure'     => $received_pure,
            'adjusted_pure'     => $adjusted_pure,
            'balance_pure'      => $balance_pure,
            'pieces'            => (int)$r['pieces'],
            'item_description'  => (string)($r['item_description'] ?? ''),
            'source_type'       => $r['source_type'],
            'job_id'            => $r['job_id'] !== null ? (int)$r['job_id'] : null,
            'is_pending'        => $is_pending,
            'label'             => 'Issue #' . $r['id'] . ' — ' . $r['issue_date']
                                   . ' (' . $issued_pure . 'g pure, '
                                   . ($is_pending ? $balance_pure . 'g বাকি' : 'closed') . ')'
        ];
    }

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

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