<?php
/**
 * api/sales/sale_payment.php
 * Sales due payment — Cash Module 2.0
 * Date: 2026-06-05
 */
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../_core.php';
require_once __DIR__ . '/../_finance.php';

if (!is_logged_in()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'লগইন করুন']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'POST only']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) $input = [];

$sale_id         = isset($input['sale_id'])         ? (int)$input['sale_id']         : 0;
$cash_account_id = isset($input['cash_account_id']) ? (int)$input['cash_account_id'] : 0;
$amount          = isset($input['amount'])          ? (float)$input['amount']         : 0;
$note            = isset($input['note'])            ? trim($input['note'])            : '';
$payment_date    = isset($input['payment_date'])    ? $input['payment_date']          : date('Y-m-d');
$reference_no    = isset($input['reference_no'])    ? trim($input['reference_no'])    : null;
$user_id         = $_SESSION['user_id'] ?? null;

if (!$sale_id || !$cash_account_id || $amount <= 0) {
    echo json_encode(['ok' => false, 'error' => 'sale_id, cash_account_id ও amount আবশ্যক']);
    exit;
}

// Sale যাচাই
$stmt = $pdo->prepare("
    SELECT id, invoice_no, customer_id, grand_total, paid_total, due_amount, payment_status
    FROM sales
    WHERE id = ?
");
$stmt->execute([$sale_id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$sale) {
    echo json_encode(['ok' => false, 'error' => 'Sale পাওয়া যায়নি']);
    exit;
}
if ($sale['payment_status'] === 'paid') {
    echo json_encode(['ok' => false, 'error' => 'এই বিক্রয় ইতিমধ্যে সম্পূর্ণ পরিশোধিত']);
    exit;
}
$current_due = (float)$sale['due_amount'];
if ($amount > $current_due + 0.01) {
    echo json_encode(['ok' => false, 'error' => 'অতিরিক্ত পরিশোধ সম্ভব নয়। বকেয়া: ৳' . number_format($current_due, 2)]);
    exit;
}

try {
    $pdo->beginTransaction();

    // SALE_RECEIPT category
    $catStmt = $pdo->prepare("SELECT id FROM cash_categories WHERE category_code = 'SALE_RECEIPT' LIMIT 1");
    $catStmt->execute();
    $saleCatId = (int)$catStmt->fetchColumn();
    if ($saleCatId <= 0) throw new Exception('SALE_RECEIPT category পাওয়া যায়নি');

    // Cash transaction (IN)
    $cash_txn_id = gs_insert_cash_transaction($pdo, [
        'category_id'      => $saleCatId,
        'cash_account_id'  => $cash_account_id,
        'amount'           => $amount,
        'transaction_date' => $payment_date,
        'note'             => 'বিক্রয় বকেয়া আদায় #' . $sale['invoice_no'] . ($note ? ' — ' . $note : ''),
        'reference_type'   => 'SALE',
        'reference_id'     => $sale_id,
        'party_id'         => $sale['customer_id'],
        'created_by'       => $user_id,
    ]);

    gs_recalc_cash_account($pdo, $cash_account_id);

    // sale_payments তে নতুন row
    $payStmt = $pdo->prepare("
        INSERT INTO sale_payments (sale_id, cash_account_id, amount, reference_no, cash_transaction_id)
        VALUES (?, ?, ?, ?, ?)
    ");
    $payStmt->execute([$sale_id, $cash_account_id, $amount, $reference_no ?: null, $cash_txn_id]);

    // sales table update
    $new_paid   = (float)$sale['paid_total'] + $amount;
    $new_due    = (float)$sale['grand_total'] - $new_paid;
    if ($new_due < 0) $new_due = 0;
    $new_status = ($new_due <= 0.01) ? 'paid' : (($new_paid > 0) ? 'partial' : 'due');

    $pdo->prepare("
        UPDATE sales SET paid_total=?, due_amount=?, payment_status=? WHERE id=?
    ")->execute([$new_paid, $new_due, $new_status, $sale_id]);

    $pdo->commit();

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

} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}