<?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';
require_once __DIR__ . '/../../config/session.php';

if (function_exists('session_start_if_not_started')) {
    session_start_if_not_started();
}

if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'status' => 401,
        'success' => false,
        'message' => 'লগইন প্রয়োজন'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'status' => 405,
        'success' => false,
        'message' => 'শুধু POST অনুরোধ গ্রহণযোগ্য'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

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

$pledge_id       = (int)($data['pledge_id'] ?? 0);
$payment_date    = trim($data['payment_date'] ?? date('Y-m-d'));
$payment_amount  = (float)($data['payment_amount'] ?? 0);
$cash_account_id = (int)($data['cash_account_id'] ?? 0);
$note            = trim($data['note'] ?? '');

if ($pledge_id <= 0) {
    echo json_encode([
        'status' => 400,
        'success' => false,
        'message' => 'Pledge ID দিন'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($payment_amount <= 0) {
    echo json_encode([
        'status' => 400,
        'success' => false,
        'message' => 'Payment amount দিন'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($cash_account_id <= 0) {
    echo json_encode([
        'status' => 400,
        'success' => false,
        'message' => 'Cash account সিলেক্ট করুন'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

function date_diff_days_safe(string $fromDate, string $toDate): int {
    $from = strtotime($fromDate . ' 00:00:00');
    $to   = strtotime($toDate . ' 00:00:00');

    if ($from === false || $to === false || $to < $from) {
        return 0;
    }

    return (int) floor(($to - $from) / 86400);
}

try {
    $pdo->beginTransaction();

    $pledgeStmt = $pdo->prepare("
        SELECT
            id,
            pledge_code,
            pledge_date,
            party_id,
            loan_amount,
            outstanding_principal,
            interest_rate,
            last_interest_date,
            status
        FROM pledges
        WHERE id = ?
        LIMIT 1
    ");
    $pledgeStmt->execute([$pledge_id]);
    $pledge = $pledgeStmt->fetch(PDO::FETCH_ASSOC);

    if (!$pledge) {
        throw new Exception('Pledge পাওয়া যায়নি');
    }

    if (($pledge['status'] ?? 'OPEN') === 'CLOSED') {
        throw new Exception('Closed pledge-এ payment নেওয়া যাবে না');
    }

    $cashStmt = $pdo->prepare("
        SELECT id, account_name
        FROM cash_accounts
        WHERE id = ?
        LIMIT 1
    ");
    $cashStmt->execute([$cash_account_id]);
    $cash = $cashStmt->fetch(PDO::FETCH_ASSOC);

    if (!$cash) {
        throw new Exception('Cash account পাওয়া যায়নি');
    }

    $outstanding_before = (float)($pledge['outstanding_principal'] ?? 0);
    $interest_rate      = (float)($pledge['interest_rate'] ?? 0);

    if ($outstanding_before <= 0) {
        throw new Exception('এই pledge-এ আর কোন principal বাকি নেই');
    }

    $base_interest_date = !empty($pledge['last_interest_date'])
        ? $pledge['last_interest_date']
        : $pledge['pledge_date'];

    $days = date_diff_days_safe($base_interest_date, $payment_date);

    // Monthly rate থেকে daily-style proportional interest
    $interest_due = round($outstanding_before * ($interest_rate / 100) * ($days / 30), 2);

    // আগে interest কাটবে
    $interest_paid = min($payment_amount, $interest_due);
    $remaining_after_interest = round($payment_amount - $interest_paid, 2);

    if ($remaining_after_interest < 0) {
        $remaining_after_interest = 0;
    }

    // তারপর principal কমবে
    $principal_paid = min($remaining_after_interest, $outstanding_before);
    $principal_paid = round($principal_paid, 2);

    $outstanding_after = round($outstanding_before - $principal_paid, 2);
    if ($outstanding_after < 0) {
        $outstanding_after = 0;
    }

    // Auto close when principal fully paid
    $newStatus = ($outstanding_after <= 0) ? 'CLOSED' : 'OPEN';
    $closedAt  = ($outstanding_after <= 0) ? ($payment_date . ' 00:00:00') : null;

    $paymentInsert = $pdo->prepare("
        INSERT INTO pledge_payments
        (
            pledge_id,
            payment_date,
            payment_amount,
            interest_paid,
            principal_paid,
            cash_account_id,
            note
        )
        VALUES
        (?, ?, ?, ?, ?, ?, ?)
    ");
    $paymentInsert->execute([
        $pledge_id,
        $payment_date,
        $payment_amount,
        $interest_paid,
        $principal_paid,
        $cash_account_id,
        $note
    ]);

    $payment_id = (int) $pdo->lastInsertId();

    $pledgeUpdate = $pdo->prepare("
        UPDATE pledges
        SET
            outstanding_principal = ?,
            last_interest_date = ?,
            status = ?,
            closed_at = ?
        WHERE id = ?
    ");
    $pledgeUpdate->execute([
        $outstanding_after,
        $payment_date,
        $newStatus,
        $closedAt,
        $pledge_id
    ]);

    $txnNote = 'Pledge Payment #' . $payment_id . ' (' . ($pledge['pledge_code'] ?? '') . ')';
    if ($note !== '') {
        $txnNote .= ' — ' . $note;
    }

    $cashTxn = $pdo->prepare("
        INSERT INTO cash_transactions
        (
            transaction_date,
            cash_account_id,
            transaction_type_id,
            transaction_type,
            type,
            amount,
            note,
            reference_type,
            reference_id,
            is_reversal
        )
        VALUES
        (?, ?, 5, 'IN', 'cash_in', ?, ?, 'PLEDGE_PAYMENT', ?, 0)
    ");
    $cashTxn->execute([
        $payment_date,
        $cash_account_id,
        $payment_amount,
        $txnNote,
        $payment_id
    ]);

    $balanceUpdate = $pdo->prepare("
        UPDATE cash_accounts
        SET current_balance =
            opening_balance + COALESCE((
                SELECT SUM(
                    CASE
                        WHEN transaction_type = 'IN' THEN amount
                        ELSE -amount
                    END
                )
                FROM cash_transactions
                WHERE cash_account_id = ?
                  AND deleted_at IS NULL
                  AND is_reversal = 0
            ), 0)
        WHERE id = ?
    ");
    $balanceUpdate->execute([$cash_account_id, $cash_account_id]);

    $pdo->commit();

    echo json_encode([
        'status' => 200,
        'success' => true,
        'message' => 'Pledge payment সফলভাবে সেভ হয়েছে',
        'data' => [
            'payment_id' => $payment_id,
            'pledge_id' => $pledge_id,
            'pledge_code' => $pledge['pledge_code'] ?? '',
            'days' => $days,
            'interest_due' => $interest_due,
            'interest_paid' => $interest_paid,
            'principal_paid' => $principal_paid,
            'payment_amount' => $payment_amount,
            'outstanding_before' => $outstanding_before,
            'outstanding_after' => $outstanding_after,
            'last_interest_date' => $payment_date,
            'status' => $newStatus,
            'closed_at' => $closedAt
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    echo json_encode([
        'status' => 500,
        'success' => false,
        'message' => 'সার্ভার সমস্যা: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>