<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

function send($ok,$msg,$data=[],$code=200){
    http_response_code($code);
    echo json_encode(['success'=>$ok,'message'=>$msg,'data'=>$data],JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (function_exists('session_start_if_not_started')) session_start_if_not_started();
if (function_exists('is_logged_in') && !is_logged_in()) send(false,'লগইন প্রয়োজন',[],401);

try {
    if(($_SERVER['REQUEST_METHOD'] ?? '')!=='POST') send(false,'Invalid method',[],405);

    $in = json_decode(file_get_contents('php://input'),true);
    if(!is_array($in)) send(false,'Invalid JSON',[],400);

    $pledge_id     = (int)($in['pledge_id'] ?? 0);
    $pledge_date   = trim((string)($in['pledge_date'] ?? ''));
    $loan_amount   = round((float)($in['loan_amount'] ?? 0),2);
    $interest_rate = round((float)($in['interest_rate'] ?? 0),2);

    if(!$pledge_id) send(false,'Pledge ID নেই',[],422);
    if(!$pledge_date) send(false,'তারিখ দিন',[],422);
    if($loan_amount<=0) send(false,'ঋণের পরিমাণ দিন',[],422);
    if($interest_rate<0) send(false,'সুদের হার সঠিক নয়',[],422);

    $cur = $pdo->prepare('SELECT id,status,loan_amount,outstanding_principal FROM pawn_pledges WHERE id=? LIMIT 1');
    $cur->execute([$pledge_id]);
    $pledge = $cur->fetch(PDO::FETCH_ASSOC);

    if(!$pledge) send(false,'বন্ধক পাওয়া যায়নি',[],404);
    if(strtoupper((string)$pledge['status'])==='CLOSED') send(false,'বন্ধ বন্ধক এডিট করা যাবে না',[],422);

    $old_loan = (float)$pledge['loan_amount'];
    $old_outstanding = (float)$pledge['outstanding_principal'];
    $diff = $loan_amount - $old_loan;
    $new_outstanding = max(0, $old_outstanding + $diff);

    $st = $pdo->prepare('UPDATE pawn_pledges SET pledge_date=?, loan_amount=?, outstanding_principal=?, interest_rate=? WHERE id=?');
    $st->execute([$pledge_date, $loan_amount, round($new_outstanding,2), $interest_rate, $pledge_id]);

    send(true,'তথ্য আপডেট হয়েছে ✅',[
        'pledge_id' => $pledge_id,
        'loan_amount' => $loan_amount,
        'outstanding' => round($new_outstanding,2),
        'interest_rate' => $interest_rate,
        'pledge_date' => $pledge_date
    ]);
} catch(Throwable $e){
    send(false,'Server error: '.$e->getMessage(),[],500);
}
