<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

$pledge_id = 0;

if (isset($_GET['pledge_id'])) {
    $pledge_id = (int)$_GET['pledge_id'];
} elseif (isset($_GET['id'])) {
    $pledge_id = (int)$_GET['id'];
}

if ($pledge_id <= 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid pledge id'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $stmt = $pdo->prepare("
        SELECT
            p.id,
            p.pledge_code,
            p.manual_barcode,
            p.party_id,
            p.pledge_date,
            p.karat,
            p.gross_weight,
            p.system_purity,
            p.deduction,
            p.actual_purity,
            p.pure_weight,
            p.gold_value,
            p.loan_amount,
            p.outstanding_principal,
            p.interest_rate,
            p.location_id,
            p.status,
            p.holding_status,
            p.closed_at,
            p.created_at,
            COALESCE(pa.name, '') AS party_name,
            COALESCE(pa.phone, '') AS party_phone
        FROM pawn_pledges p
        LEFT JOIN parties pa ON pa.id = p.party_id
        WHERE p.id = ?
        LIMIT 1
    ");
    $stmt->execute([$pledge_id]);
    $pledge = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$pledge) {
        echo json_encode([
            'success' => false,
            'message' => 'Pledge পাওয়া যায়নি'
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT
            id,
            pledge_id,
            payment_date,
            amount,
            interest_paid,
            principal_paid,
            cash_account_id,
            note,
            created_at
        FROM pawn_payments
        WHERE pledge_id = ?
        ORDER BY id DESC
    ");
    $stmt->execute([$pledge_id]);
    $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $total_paid = 0;
    $total_interest_paid = 0;
    $total_principal_paid = 0;

    foreach ($payments as $row) {
        $amount = (float)($row['amount'] ?? 0);
        $interest = (float)($row['interest_paid'] ?? 0);
        $principal = (float)($row['principal_paid'] ?? 0);

        if ($principal <= 0 && $interest <= 0 && $amount > 0) {
            $principal = $amount;
        }

        $total_paid += $amount;
        $total_interest_paid += $interest;
        $total_principal_paid += $principal;
    }

    echo json_encode([
        'success' => true,
        'data' => [
            'pledge' => $pledge,
            'payments' => $payments,
            'summary' => [
                'total_paid' => round($total_paid, 2),
                'total_interest_paid' => round($total_interest_paid, 2),
                'total_principal_paid' => round($total_principal_paid, 2)
            ]
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Server error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}