<?php
/**
 * api/pawn/pledge_add.php
 * POST JSON — pawn.php থেকে call হয়
 * Response format: {success, data: {pledge_code, pledge_id}}
 */
require_once __DIR__ . '/../../config/db.php';
header('Content-Type: application/json; charset=utf-8');
if (session_status() === PHP_SESSION_NONE) session_start();
$user_id = $_SESSION['user_id'] ?? 1;
$ip      = $_SERVER['REMOTE_ADDR'] ?? '';

// JSON body পড়া
$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);
if (empty($data)) $data = $_POST;
if (empty($data)) { echo json_encode(['success'=>false,'message'=>'কোনো data পাওয়া যায়নি।']); exit; }

// Fields
$party_id        = (int)   ($data['party_id']        ?? 0);
$pledge_date     =         ($data['pledge_date']      ?? date('Y-m-d'));
$loan_amount     = (float) ($data['loan_amount']      ?? 0);
$interest_rate   = (float) ($data['interest_rate']    ?? 2);
$cash_account_id = (int)   ($data['cash_account_id']  ?? 0);
$holding_status  = trim(   ($data['holding_status']   ?? 'SHOWROOM'));
$locker_id       = !empty($data['locker_id']) ? (int)$data['locker_id'] : null;
$note            = trim(   ($data['note']             ?? ''));
$manual_barcode  = trim(   ($data['manual_barcode']   ?? ''));
$location_note   = trim(   ($data['location_note']    ?? ''));
$items           =         ($data['items']            ?? []);

// Items থেকে gross_weight, karat, purity বের করা
$total_gross = 0;
$total_pure  = 0;
$total_value = 0;
$karat       = '22K';
$system_purity = 91.6;
$deduction     = 0;
$actual_purity = 91.6;

if (!empty($items) && is_array($items)) {
    foreach ($items as $it) {
        $total_gross += (float)($it['gross_weight'] ?? 0);
        $total_pure  += (float)($it['net_weight']   ?? 0);
        $total_value += (float)($it['estimated_value'] ?? 0);
    }
    // প্রথম আইটেম থেকে karat/purity নেওয়া
    $first = $items[0];
    $karat          = $first['karat']          ?? '22K';
    $system_purity  = (float)($first['system_purity']  ?? 91.6);
    $deduction      = (float)($first['deduction']      ?? 0);
    $actual_purity  = (float)($first['actual_purity']  ?? 91.6);
}

// Validation
if ($party_id <= 0)        { echo json_encode(['success'=>false,'message'=>'পার্টি নির্বাচন করুন।']); exit; }
if ($total_gross <= 0)     { echo json_encode(['success'=>false,'message'=>'ওজন দিন।']); exit; }
if ($loan_amount  <= 0)    { echo json_encode(['success'=>false,'message'=>'ঋণের পরিমাণ দিন।']); exit; }
if ($cash_account_id <= 0) { echo json_encode(['success'=>false,'message'=>'Cash account নির্বাচন করুন।']); exit; }

// Party check
$pc = $pdo->prepare("SELECT id, name FROM parties WHERE id=? AND deleted_at IS NULL LIMIT 1");
$pc->execute([$party_id]);
$party = $pc->fetch(PDO::FETCH_ASSOC);
if (!$party) { echo json_encode(['success'=>false,'message'=>'পার্টি পাওয়া যায়নি।']); exit; }

// Pledge code
$ym     = date('Ym');
$prefix = 'PLG-' . $ym . '-';
$cnt    = (int)$pdo->query("SELECT COUNT(*) FROM pawn_pledges WHERE pledge_code LIKE '{$prefix}%'")->fetchColumn();
$pledge_code = $prefix . str_pad($cnt + 1, 4, '0', STR_PAD_LEFT);

// Voucher
function makeVoucher(PDO $pdo): string {
    $p = 'CV-' . date('Ym') . '-';
    $c = (int)$pdo->query("SELECT COUNT(*) FROM cash_transactions WHERE voucher_no LIKE '{$p}%'")->fetchColumn();
    return $p . str_pad($c + 1, 4, '0', STR_PAD_LEFT);
}

try {
    $pdo->beginTransaction();

    // 1. pawn_pledges insert
    $ins = $pdo->prepare("
        INSERT INTO pawn_pledges
            (pledge_code, manual_barcode, party_id, pledge_date, karat,
             gross_weight, system_purity, deduction, actual_purity, pure_weight,
             gold_value, loan_amount, outstanding_principal, interest_rate,
             status, holding_status, locker_id, location_note, note, created_at)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,'OPEN',?,?,?,?,NOW())
    ");
    $ins->execute([
        $pledge_code, $manual_barcode, $party_id, $pledge_date, $karat,
        round($total_gross, 3), $system_purity, $deduction, $actual_purity, round($total_pure, 3),
        round($total_value, 2), $loan_amount, $loan_amount, $interest_rate,
        $holding_status, $locker_id, $location_note, $note
    ]);
    $pledge_id = (int)$pdo->lastInsertId();

    // 2. pledge_items insert
    if (!empty($items) && is_array($items)) {
        $si = $pdo->prepare("
            INSERT INTO pledge_items
                (pledge_id, item_name, quantity, gross_weight, net_weight, purity, remarks, estimated_value, created_at)
            VALUES (?,?,?,?,?,?,?,?,NOW())
        ");
        foreach ($items as $it) {
            $si->execute([
                $pledge_id,
                $it['item_name']        ?? '—',
                (int)($it['quantity']   ?? 1),
                (float)($it['gross_weight'] ?? 0),
                (float)($it['net_weight']   ?? 0),
                $it['karat']            ?? $karat,
                $it['remarks']          ?? '',
                (float)($it['estimated_value'] ?? 0),
            ]);
        }
    }

    // 3. Cash OUT — গ্রাহককে ঋণ দেওয়া
    // category_id=11 (PLEDGE_CASH_TO_CUSTOMER) বা fallback
    $cat_row = $pdo->query("SELECT id FROM cash_categories WHERE id=11 LIMIT 1")->fetchColumn();
    $cat_id  = $cat_row ? 11 : (int)$pdo->query("SELECT id FROM cash_categories WHERE direction='OUT' ORDER BY id LIMIT 1")->fetchColumn();
    if (!$cat_id) $cat_id = 1;

    $voucher   = makeVoucher($pdo);
    $txn_note  = 'বন্ধক ঋণ প্রদান | ' . $pledge_code . ' | ' . $party['name'];
    if ($note) $txn_note .= ' | ' . $note;

    $pdo->prepare("
        INSERT INTO cash_transactions
            (voucher_no, transaction_date, cash_account_id, category_id, direction,
             amount, note, reference_type, reference_id, party_id, pledge_id,
             created_by, created_ip, created_at)
        VALUES (?,?,?,?,'OUT',?,?,?,?,?,?,?,?,NOW())
    ")->execute([
        $voucher, $pledge_date, $cash_account_id, $cat_id,
        $loan_amount, $txn_note,
        'PLEDGE', $pledge_id, $party_id, $pledge_id,
        $user_id, $ip
    ]);

    // 4. Cash balance update
    $pdo->prepare("UPDATE cash_accounts SET current_balance=current_balance-? WHERE id=?")
        ->execute([$loan_amount, $cash_account_id]);

    $pdo->commit();

    // JS expects: res.success + res.data.pledge_code
    echo json_encode([
        'success' => true,
        'message' => 'বন্ধক সফলভাবে সংরক্ষিত হয়েছে।',
        'data'    => [
            'pledge_id'   => $pledge_id,
            'pledge_code' => $pledge_code,
            'party_name'  => $party['name'],
            'loan_amount' => $loan_amount,
        ]
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['success'=>false,'message'=>'DB error: '.$e->getMessage()]);
}