<?php
// File: /public_html/erp.jewellersbd.com/api/pawn/pledge_locker_settle.php
// Locker settlement save
// Audit Added: pledges UPDATE

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();
} elseif (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function locker_settle_response($status, $success, $message, $data = null)
{
    http_response_code((int)$status);
    echo json_encode([
        'status'  => (int)$status,
        'success' => (bool)$success,
        'message' => $message,
        'data'    => $data
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * Safe Audit Logger
 * Audit fail হলেও settlement বন্ধ হবে না।
 */
function locker_settle_safe_audit_log($pdo, $tableName, $recordId, $action, $changedBy, $note = '')
{
    try {
        if (!$pdo || !($pdo instanceof PDO)) {
            return;
        }

        $ipAddress = $_SERVER['REMOTE_ADDR'] ?? '';

        $stmt = $pdo->prepare("
            INSERT INTO audit_log
                (table_name, record_id, action, changed_by, changed_at, ip_address, note)
            VALUES
                (:table_name, :record_id, :action, :changed_by, NOW(), :ip_address, :note)
        ");

        $stmt->execute([
            ':table_name' => $tableName,
            ':record_id'  => (int)$recordId,
            ':action'     => $action,
            ':changed_by' => (int)$changedBy,
            ':ip_address' => $ipAddress,
            ':note'       => $note
        ]);

    } catch (Throwable $e) {
        return;
    }
}

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    locker_settle_response(401, false, 'লগইন প্রয়োজন');
}

$userId = (int)($_SESSION['user_id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    locker_settle_response(405, false, 'শুধু POST অনুরোধ গ্রহণযোগ্য');
}

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

if (!is_array($data)) {
    locker_settle_response(400, false, 'Invalid JSON');
}

$pledge_id    = (int)($data['pledge_id'] ?? 0);
$locker_value = round((float)($data['locker_value'] ?? 0), 2);
$note         = trim((string)($data['note'] ?? ''));

if ($pledge_id <= 0) {
    locker_settle_response(400, false, 'Pledge ID দিন');
}

if ($locker_value <= 0) {
    locker_settle_response(400, false, 'Locker value দিন');
}

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("
        SELECT
            id,
            pledge_code,
            loan_amount,
            holding_status,
            status,
            locker_value,
            locker_profit_loss
        FROM pledges
        WHERE id = ?
        LIMIT 1
        FOR UPDATE
    ");
    $stmt->execute([$pledge_id]);
    $pledge = $stmt->fetch(PDO::FETCH_ASSOC);

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

    if (($pledge['holding_status'] ?? 'SHOWROOM') !== 'LOCKER') {
        throw new Exception('এই pledge এখনো LOCKER-এ নেই');
    }

    $loan_amount = round((float)($pledge['loan_amount'] ?? 0), 2);
    $old_locker_value = round((float)($pledge['locker_value'] ?? 0), 2);
    $old_profit_loss = round((float)($pledge['locker_profit_loss'] ?? 0), 2);

    $profit_loss = round($locker_value - $loan_amount, 2);

    $upd = $pdo->prepare("
        UPDATE pledges
        SET
            locker_value = ?,
            locker_profit_loss = ?,
            locker_closed_at = NOW(),
            showroom_note = CASE
                WHEN showroom_note IS NULL OR showroom_note = ''
                THEN ?
                ELSE CONCAT(showroom_note, '\n', ?)
            END
        WHERE id = ?
    ");

    $upd->execute([
        $locker_value,
        $profit_loss,
        $note,
        $note,
        $pledge_id
    ]);

    $auditNote = "Locker settlement saved"
        . " | Pledge: " . ($pledge['pledge_code'] ?? '')
        . " | Loan Amount: " . number_format($loan_amount, 2)
        . " | Old Locker Value: " . number_format($old_locker_value, 2)
        . " | New Locker Value: " . number_format($locker_value, 2)
        . " | Old Profit/Loss: " . number_format($old_profit_loss, 2)
        . " | New Profit/Loss: " . number_format($profit_loss, 2);

    if ($note !== '') {
        $auditNote .= " | Note: " . $note;
    }

    locker_settle_safe_audit_log(
        $pdo,
        'pledges',
        $pledge_id,
        'UPDATE',
        $userId,
        $auditNote
    );

    $pdo->commit();

    echo json_encode([
        'status' => 200,
        'success' => true,
        'message' => 'Locker settlement সফলভাবে সেভ হয়েছে',
        'data' => [
            'pledge_id' => $pledge_id,
            'pledge_code' => $pledge['pledge_code'] ?? '',
            'loan_amount' => $loan_amount,
            'locker_value' => $locker_value,
            'locker_profit_loss' => $profit_loss,
            'locker_closed_at' => date('Y-m-d H:i:s')
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }

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