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

if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    die(json_encode(['success' => false, 'message' => 'Unauthorized access']));
}

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

$approval_id = $_POST['approval_id'];
$action = $_POST['action'];
$file_number = $_POST['file_number'];
$new_amount = $_POST['new_amount'];
$user_id = $_SESSION['user_id'];

try {
    $conn->begin_transaction();

    if ($action === 'approve') {
        // Get all non-operational costs for the file
        $sql = "SELECT SUM(charge) as total_non_operational 
                FROM pre_proforma 
                WHERE file_number = ? 
                AND category = 'Non-Operational'";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $file_number);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $total_non_operational = $row['total_non_operational'] ?? 0;

        // Calculate new agency fee (operational cost)
        $new_agency_fee = $new_amount - $total_non_operational;

        // Update files table
        $update_file = $conn->prepare("UPDATE files SET all_in_amount = ? WHERE file_number = ?");
        $update_file->bind_param("is", $new_amount, $file_number);
        $update_file->execute();

        // Update agency fee in pre_proforma
        $update_proforma = $conn->prepare("
            UPDATE pre_proforma 
            SET charge = ?, 
                updated_date = NOW(),
                update_count = update_count + 1
            WHERE file_number = ? 
            AND category = 'Operational' 
            AND cost_code = '1-101'
        ");
        $update_proforma->bind_param("ds", $new_agency_fee, $file_number);
        $update_proforma->execute();

        // Update approval status
        $update_approval = $conn->prepare("
            UPDATE pending_approvals 
            SET approved = 'Approved',
                approver = ?,
                approved_date = NOW()
            WHERE id = ?
        ");
        $update_approval->bind_param("si", $_SESSION['full_name'], $approval_id);
        $update_approval->execute();

        // Create notification
        $notification = "All-In amount updated for file {$file_number}";
        $insert_notification = $conn->prepare("
            INSERT INTO notifications (
                file_id, 
                file_number, 
                notif_message, 
                created_at
            ) VALUES (
                (SELECT id FROM files WHERE file_number = ?),
                ?,
                ?,
                NOW()
            )
        ");
        $insert_notification->bind_param("sss", $file_number, $file_number, $notification);
        $insert_notification->execute();

        $conn->commit();
        $_SESSION['success_message'] = "All-In amount updated successfully";
        header('Location: allin_list.php');
        exit();

    } elseif ($action === 'reject') {
        // Update approval status to rejected
        $update_approval = $conn->prepare("
            UPDATE pending_approvals 
            SET approved = 'Rejected',
                approver = ?,
                approved_date = NOW()
            WHERE id = ?
        ");
        $update_approval->bind_param("si", $_SESSION['full_name'], $approval_id);
        $update_approval->execute();

        $conn->commit();
        $_SESSION['success_message'] = "All-In amount request rejected";
        header('Location: allin_list.php');
        exit();
    }

} catch (Exception $e) {
    $conn->rollback();
    error_log("Error processing all-in approval: " . $e->getMessage());
    $_SESSION['error_message'] = "Error processing request: " . $e->getMessage();
    header('Location: allin_list.php');
    exit();
}

?>