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

// Check if user is logged in and has admin privileges
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 2])) { // Admin and General Manager
    header('Location: login.php');
    exit();
}

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);
$user_details = $result_user_details->fetch_assoc();

// Process approval/rejection
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $approval_id = $_POST['approval_id'];
    $action = $_POST['action'];
    $file_number = $_POST['file_number'];
    $new_amount = $_POST['new_amount'];
    
    try {
        $conn->begin_transaction();
        
        if ($action === 'approve') {
            // Update the file's all_in_amount
            $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 approval status
            $update_approval = $conn->prepare("
                UPDATE pending_approvals 
                SET approved = 'Approved', 
                    approver = ?, 
                    approved_date = NOW() 
                WHERE id = ?
            ");
            $update_approval->bind_param("si", $user_details['full_name'], $approval_id);
            $update_approval->execute();
            
            $conn->commit();
            $_SESSION['success_message'] = "All-In amount approved successfully.";
            
        } 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", $user_details['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();
        $_SESSION['error_message'] = "Error processing request: " . $e->getMessage();
    }
}

// Get the approval details
if (!isset($_GET['id'])) {
    header('Location: allin_list.php');
    exit();
}

$approval_id = $_GET['id'];
$sql = "SELECT pa.*, f.all_in_amount as current_amount 
        FROM pending_approvals pa
        JOIN pre_proforma f ON pa.file_number = f.file_number
        WHERE pa.id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $approval_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: allin_list.php');
    exit();
}

$approval = $result->fetch_assoc();

// Set system name
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result = $conn->query($sql);
$system_name = $result->num_rows > 0 ? $result->fetch_assoc()['setting_value'] : "Royal Freight";
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All In Amount Approval')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Files', 'title' => 'All In Amount Approval')); ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">All In Amount Approval</h4>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">File Number</label>
                                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($approval['file_number']); ?>" readonly>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Current All In Amount</label>
                                                <input type="text" class="form-control" value="<?php echo number_format($approval['current_amount'], 2); ?>" readonly>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Proposed All In Amount</label>
                                                <input type="text" class="form-control" value="<?php echo number_format($approval['new_all_in_amount'], 2); ?>" readonly>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">Proposed By</label>
                                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($approval['proposed_by']); ?>" readonly>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Proposed Date</label>
                                                <input type="text" class="form-control" value="<?php echo date('Y-m-d H:i:s', strtotime($approval['proposed_date'])); ?>" readonly>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-12">
                                            <form method="POST" action="process_allin_approval.php" id="approvalForm">
                                                <input type="hidden" name="approval_id" value="<?php echo $approval['id']; ?>">
                                                <input type="hidden" name="file_number" value="<?php echo $approval['file_number']; ?>">
                                                <input type="hidden" name="new_amount" value="<?php echo $approval['new_all_in_amount']; ?>">
                                                <div class="d-flex justify-content-end gap-2">
                                                    <button type="submit" name="action" value="reject" class="btn btn-danger" 
                                                            onclick="return confirm('Are you sure you want to reject this request?')">
                                                        Reject
                                                    </button>
                                                    <button type="submit" name="action" value="approve" class="btn btn-success"
                                                            onclick="return confirm('Are you sure you want to approve the new All-In amount?')">
                                                        Approve
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>