<?php
/**
 * api/purchases/purchase_payment.php
 * Purchase due payment — Cash Module 2.0
 */
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';
require_once __DIR__ . '/../_finance.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success'=>false,'message'=>'Method not allowed']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

$purchase_id     = isset($data['purchase_id'])     ? (int)$data['purchase_id']     : 0;
$cash_account_id = isset($data['cash_account_id']) ? (int)$data['cash_account_id'] : 0;
$amount          = isset($data['amount'])          ? (float)$data['amount']         : 0;
$note            = isset($data['note'])            ? trim($data['note'])            : '';
$payment_date    = isset($data['payment_date'])    ? $data['payment_date']          : date('Y-m-d');

if (!$purchase_id || !$cash_account_id || $amount <= 0) {
    echo json_encode(['success'=>false,'message'=>'অবৈধ তথ্য। purchase_id, cash_account_id ও amount আবশ্যক।']);
    exit;
}

// Purchase যাচাই
$stmt = $pdo->prepare("SELECT id, item_name, total_amount, paid_amount, due_amount, payment_status FROM purchases WHERE id = ? AND deleted_at IS NULL");
$stmt->execute([$purchase_id]);
$purchase = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$purchase) {
    echo json_encode(['success'=>false,'message'=>'Purchase পাওয়া যায়নি।']);
    exit;
}
if ($purchase['payment_status'] === 'paid') {
    echo json_encode(['success'=>false,'message'=>'এই purchase ইতিমধ্যে সম্পূর্ণ পরিশোধিত।']);
    exit;
}

$current_due = (float)$purchase['due_amount'];
if ($amount > $current_due + 0.01) {
    echo json_encode(['success'=>false,'message'=>'অতিরিক্ত পরিশোধ সম্ভব নয়। বকেয়া: ৳' . number_format($current_due, 2)]);
    exit;
}

try {
    $pdo->beginTransaction();

    // PURCHASE_PAYMENT category id
    $catStmt = $pdo->prepare("SELECT id FROM cash_categories WHERE category_code = 'PURCHASE_PAYMENT' LIMIT 1");
    $catStmt->execute();
    $purchaseCatId = (int)$catStmt->fetchColumn();

    if ($purchaseCatId <= 0) {
        throw new Exception('PURCHASE_PAYMENT category পাওয়া যায়নি');
    }

    // Cash Module 2.0
    gs_insert_cash_transaction($pdo, [
        'category_id'      => $purchaseCatId,
        'cash_account_id'  => $cash_account_id,
        'amount'           => $amount,
        'transaction_date' => $payment_date,
        'note'             => 'ক্রয় পরিশোধ #' . $purchase_id . ($note ? ' — ' . $note : '') . ' (' . $purchase['item_name'] . ')',
        'reference_type'   => 'PURCHASE',
        'reference_id'     => $purchase_id,
        'created_by'       => $_SESSION['user_id'] ?? null,
    ]);

    gs_recalc_cash_accounts($pdo, [$cash_account_id]);

    // purchases update
    $new_paid   = (float)$purchase['paid_amount'] + $amount;
    $new_due    = (float)$purchase['total_amount'] - $new_paid;
    if ($new_due < 0) $new_due = 0;
    $new_status = ($new_due <= 0.01) ? 'paid' : (($new_paid > 0) ? 'partial' : 'due');

    $upd = $pdo->prepare("UPDATE purchases SET paid_amount=?, due_amount=?, payment_status=? WHERE id=?");
    $upd->execute([$new_paid, $new_due, $new_status, $purchase_id]);

    $pdo->commit();

    echo json_encode([
        'success'        => true,
        'message'        => 'Payment সফলভাবে সংরক্ষিত হয়েছে।',
        'new_paid'       => $new_paid,
        'new_due'        => $new_due,
        'payment_status' => $new_status,
    ], JSON_UNESCAPED_UNICODE);

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