<?php
// save_allin_update.php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    die(json_encode(['success' => false, 'message' => 'Not authenticated']));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die(json_encode(['success' => false, 'message' => 'Invalid request method']));
}

$file_number = $_POST['file_number'];
$new_amount = $_POST['new_all_in_amount'];
$user_id = $_SESSION['user_id'];

try {
    // Check if file is not in proforma
    $check_sql = "SELECT COUNT(*) as count FROM proforma WHERE file_number = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("s", $file_number);
    $check_stmt->execute();
    $result = $check_stmt->get_result();
    $row = $result->fetch_assoc();

    if ($row['count'] > 0) {
        die(json_encode([
            'success' => false,
            'message' => 'Cannot update All-In amount for files in proforma stage'
        ]));
    }

    // Insert into pending_approvals
    $sql = "INSERT INTO pending_approvals (
                file_number, 
                new_all_in_amount, 
                proposed_by, 
                proposed_date
            ) VALUES (?, ?, ?, NOW())";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sis", $file_number, $new_amount, $_SESSION['full_name']);
    $stmt->execute();

    die(json_encode([
        'success' => true,
        'message' => 'All-In amount update request submitted for approval'
    ]));

} catch (Exception $e) {
    error_log("Error saving all-in update: " . $e->getMessage());
    die(json_encode([
        'success' => false,
        'message' => 'Error submitting update request'
    ]));
}
?>