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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

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

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Function to check user permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'edit', 'delete', 'approve', 'invoice'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice'], // General Manager
        '3' => ['view', 'edit', 'invoice'], // Operations
        '4' => ['view', 'invoice'], // Finance
        '5' => ['view', 'edit'], // Declaration Officer
        '6' => ['view'], // Shipping Line Clerk
        '7' => ['view'], // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

// Check if user has permission to approve all-in amounts
$can_approve = hasPermission($role_id, 'approve');

if (!$can_approve) {
    $_SESSION['error_message'] = "You don't have permission to approve all-in amounts.";
    header('Location: all_in_list.php');
    exit();
}

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('Y-m-d', strtotime($date));
}

// Initialize variables
$file_number = '';
$file_details = null;
$existing_all_in = 0;
$new_all_in = 0;
$non_op_costs = 0;
$currency = '$';
$all_non_op_costs = [];
$file_id = 0;
$proposer = '';
$proposed_date = '';

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $file_number = $_POST['file_number'];
    $decision = $_POST['decision']; // 'approve' or 'reject'
    $new_all_in = $_POST['new_all_in'];
    
    // Validate input
    if (empty($file_number)) {
        $_SESSION['error_message'] = "File number is required.";
        header('Location: all_in_list.php');
        exit();
    }
    
    try {
        // Begin transaction
        $conn->begin_transaction();
        
        if ($decision === 'approve') {
            // Update pending approval status
            $approve_sql = "UPDATE pending_approvals SET 
                           approved = 'Approved', 
                           approver = ?, 
                           approved_date = NOW() 
                           WHERE file_number = ?";
            $approve_stmt = $conn->prepare($approve_sql);
            $approve_stmt->bind_param('ss', $full_name, $file_number);
            $approve_stmt->execute();
            
            // Get non-operational costs total
            $sql_non_op = "SELECT SUM(charge) as total FROM pre_proforma 
                          WHERE file_number = ? AND category = 'Non-Operational'";
            $stmt_non_op = $conn->prepare($sql_non_op);
            $stmt_non_op->bind_param('s', $file_number);
            $stmt_non_op->execute();
            $result_non_op = $stmt_non_op->get_result();
            $non_op_costs = $result_non_op->fetch_assoc()['total'] ?: 0;
            
            // Calculate new agency fee (All-In - Non-Operational costs)
            $new_agency_fee = $new_all_in - $non_op_costs;
            
            // Update the all-in amount in the all_in record
            $update_all_in_sql = "UPDATE pre_proforma SET all_in_amount = ? 
                                 WHERE file_number = ? AND all_in = 'Yes'";
            $update_all_in_stmt = $conn->prepare($update_all_in_sql);
            $update_all_in_stmt->bind_param('ds', $new_all_in, $file_number);
            $update_all_in_stmt->execute();
            
            // Update the agency fee
            $update_agency_sql = "UPDATE pre_proforma SET charge = ? 
                                 WHERE file_number = ? AND category = 'Operational' 
                                 AND cost_code = '1-101'";
            $update_agency_stmt = $conn->prepare($update_agency_sql);
            $update_agency_stmt->bind_param('ds', $new_agency_fee, $file_number);
            $update_agency_stmt->execute();
            
            $_SESSION['success_message'] = "All-In amount has been approved successfully.";
        } else {
            // Reject the pending approval
            $reject_sql = "UPDATE pending_approvals SET 
                          approved = 'Rejected', 
                          approver = ?, 
                          approved_date = NOW() 
                          WHERE file_number = ?";
            $reject_stmt = $conn->prepare($reject_sql);
            $reject_stmt->bind_param('ss', $full_name, $file_number);
            $reject_stmt->execute();
            
            $_SESSION['success_message'] = "All-In amount request has been rejected.";
        }
        
        // Commit the transaction
        $conn->commit();
        
        header('Location: all_in_list.php');
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        
        $_SESSION['error_message'] = "Error processing approval: " . $e->getMessage();
        header('Location: approve_all_in.php?file_number=' . urlencode($file_number));
        exit();
    }
} else {
    // Check if file number is provided
    if (isset($_GET['file_number']) && !empty($_GET['file_number'])) {
        $file_number = $_GET['file_number'];
        
        // Get file details
        $sql_file = "SELECT f.*, c.first_name as customer_name, pa.new_all_in_amount, pa.proposed_by, pa.proposed_date,
                     pa.approved
                    FROM files f 
                    LEFT JOIN customers c ON f.customer = c.customer_id 
                    LEFT JOIN pending_approvals pa ON f.file_number = pa.file_number
                    WHERE f.file_number = ?";
        $stmt_file = $conn->prepare($sql_file);
        $stmt_file->bind_param('s', $file_number);
        $stmt_file->execute();
        $result_file = $stmt_file->get_result();
        
        if ($result_file->num_rows > 0) {
            $file_details = $result_file->fetch_assoc();
            $file_id = $file_details['id'];
            $currency = $file_details['currency'];
            $new_all_in = $file_details['new_all_in_amount'];
            $proposer = $file_details['proposed_by'];
            $proposed_date = formatDate($file_details['proposed_date']);
            
            // Check if already approved or rejected
            $status = $file_details['approved'] ?? 'Pending';
            if ($status !== 'Pending') {
                $_SESSION['error_message'] = "This All-In amount request has already been {$status}.";
                header('Location: all_in_list.php');
                exit();
            }
            
            // Get existing all-in amount
            $sql_all_in = "SELECT all_in_amount FROM pre_proforma 
                          WHERE file_number = ? AND all_in = 'Yes' 
                          LIMIT 1";
            $stmt_all_in = $conn->prepare($sql_all_in);
            $stmt_all_in->bind_param('s', $file_number);
            $stmt_all_in->execute();
            $result_all_in = $stmt_all_in->get_result();
            
            if ($result_all_in->num_rows > 0) {
                $existing_all_in = $result_all_in->fetch_assoc()['all_in_amount'];
            }
            
            // Get non-operational costs
            $sql_non_op = "SELECT cost_code, cost_description, charge 
                          FROM pre_proforma 
                          WHERE file_number = ? AND category = 'Non-Operational'
                          ORDER BY id";
            $stmt_non_op = $conn->prepare($sql_non_op);
            $stmt_non_op->bind_param('s', $file_number);
            $stmt_non_op->execute();
            $result_non_op = $stmt_non_op->get_result();
            
            while ($row = $result_non_op->fetch_assoc()) {
                $all_non_op_costs[] = $row;
                $non_op_costs += $row['charge'];
            }
        } else {
            $_SESSION['error_message'] = "File not found.";
            header('Location: all_in_list.php');
            exit();
        }
    } else {
        $_SESSION['error_message'] = "No file specified.";
        header('Location: all_in_list.php');
        exit();
    }
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Approve All-In Amount')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .file-details {
            background-color: #f8f9fa;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .file-details .label {
            font-weight: 600;
            margin-bottom: 5px;
            color: #495057;
        }
        .form-label {
            font-weight: 500;
        }
        .costs-table {
            margin-top: 15px;
        }
        .total-row {
            font-weight: bold;
            background-color: #f8f9fa;
        }
        .comparison-box {
            background-color: #f8f9fc;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            margin-top: 20px;
        }
        .comparison-box .row {
            margin-bottom: 10px;
        }
        .current-value {
            color: #6c757d;
        }
        .new-value {
            font-weight: bold;
            color: #20c997;
        }
        .calculation-box {
            background-color: #f8f9fc;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            margin-top: 20px;
        }
        .calculation-result {
            font-weight: bold;
            font-size: 18px;
            color: #0a58ca;
        }
        .approval-info {
            padding: 10px 15px;
            background-color: #fff8dd;
            border-left: 4px solid #ffc107;
            border-radius: 0 4px 4px 0;
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Shipment Management', 'title' => 'Approve All-In Amount')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        Approve All-In Amount for File: <?php echo $file_number; ?>
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <div class="approval-info">
                                        <p class="mb-0">
                                            <strong>Request Information:</strong> This request was submitted by <strong><?php echo $proposer; ?></strong> on <?php echo $proposed_date; ?>.
                                        </p>
                                    </div>
                                    
                                    <div class="file-details">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <div class="label">File Number:</div>
                                                    <div><?php echo $file_details['file_number']; ?></div>
                                                </div>
                                                <div class="mb-3">
                                                    <div class="label">Customer:</div>
                                                    <div><?php echo $file_details['customer_name'] ?: 'N/A'; ?></div>
                                                </div>
                                                <div class="mb-0">
                                                    <div class="label">Destination:</div>
                                                    <div><?php echo $file_details['destination']; ?></div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <div class="label">Consignee:</div>
                                                    <div><?php echo $file_details['consignee_name']; ?></div>
                                                </div>
                                                <div class="mb-3">
                                                    <div class="label">Created Date:</div>
                                                    <div><?php echo formatDate($file_details['created_date']); ?></div>
                                                </div>
                                                <div class="mb-0">
                                                    <div class="label">Currency:</div>
                                                    <div><?php echo $file_details['currency']; ?></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h5 class="mt-4 mb-3">All-In Amount Comparison</h5>
                                            <div class="comparison-box">
                                                <div class="row">
                                                    <div class="col-6">Current All-In Amount:</div>
                                                    <div class="col-6 text-end current-value"><?php echo $currency . ' ' . number_format($existing_all_in, 2); ?></div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-6">Proposed All-In Amount:</div>
                                                    <div class="col-6 text-end new-value"><?php echo $currency . ' ' . number_format($new_all_in, 2); ?></div>
                                                </div>
                                                <div class="row mt-2">
                                                    <div class="col-6">Difference:</div>
                                                    <div class="col-6 text-end">
                                                        <?php
                                                        $difference = $new_all_in - $existing_all_in;
                                                        $diff_class = $difference >= 0 ? 'text-success' : 'text-danger';
                                                        $diff_sign = $difference >= 0 ? '+' : '';
                                                        echo "<span class='$diff_class'>$diff_sign" . $currency . ' ' . number_format($difference, 2) . '</span>';
                                                        ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <h5 class="mt-4 mb-3">Agency Fee Calculation</h5>
                                            <div class="calculation-box">
                                                <div class="row">
                                                    <div class="col-6">Proposed All-In Amount:</div>
                                                    <div class="col-6 text-end"><?php echo $currency . ' ' . number_format($new_all_in, 2); ?></div>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-6">Non-Operational Costs:</div>
                                                    <div class="col-6 text-end"><?php echo $currency . ' ' . number_format($non_op_costs, 2); ?></div>
                                                </div>
                                                
                                                <hr>
                                                
                                                <div class="row">
                                                    <div class="col-6">New Agency Fee:</div>
                                                    <div class="col-6 text-end calculation-result">
                                                        <?php
                                                        $new_agency_fee = $new_all_in - $non_op_costs;
                                                        $fee_class = $new_agency_fee >= 0 ? '' : 'text-danger';
                                                        echo "<span class='$fee_class'>" . $currency . ' ' . number_format($new_agency_fee, 2) . '</span>';
                                                        ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <h5 class="mt-4 mb-3">Non-Operational Costs</h5>
                                    <div class="table-responsive costs-table">
                                        <table class="table table-bordered">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Cost Code</th>
                                                    <th>Description</th>
                                                    <th class="text-end">Amount (<?php echo $currency; ?>)</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (!empty($all_non_op_costs)): ?>
                                                    <?php foreach ($all_non_op_costs as $cost): ?>
                                                    <tr>
                                                        <td><?php echo $cost['cost_code']; ?></td>
                                                        <td><?php echo $cost['cost_description']; ?></td>
                                                        <td class="text-end"><?php echo number_format($cost['charge'], 2); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="3" class="text-center">No non-operational costs found</td>
                                                    </tr>
                                                <?php endif; ?>
                                                <tr class="total-row">
                                                    <td colspan="2" class="text-end">Total Non-Operational Costs:</td>
                                                    <td class="text-end"><?php echo number_format($non_op_costs, 2); ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <?php
                                    // Check if new agency fee would be negative
                                    $new_agency_fee = $new_all_in - $non_op_costs;
                                    if ($new_agency_fee < 0):
                                    ?>
                                    <div class="alert alert-danger mt-4">
                                        <i class="ri-error-warning-line me-2"></i>
                                        <strong>Warning:</strong> The proposed All-In amount would result in a negative Agency Fee. 
                                        This is generally not recommended. Please consider rejecting this request.
                                    </div>
                                    <?php endif; ?>
                                    
                                    <form method="POST" action="" id="approval-form">
                                        <input type="hidden" name="file_number" value="<?php echo $file_number; ?>">
                                        <input type="hidden" name="new_all_in" value="<?php echo $new_all_in; ?>">
                                        
                                        <div class="row mt-4">
                                            <div class="col-12 text-end">
                                                <a href="all_in_list.php" class="btn btn-secondary me-2">Back</a>
                                                <button type="submit" name="decision" value="reject" class="btn btn-danger me-2" id="reject-btn">
                                                    <i class="ri-close-line me-1"></i> Reject
                                                </button>
                                                <button type="submit" name="decision" value="approve" class="btn btn-success" id="approve-btn" <?php echo $new_agency_fee < 0 ? 'data-warning="true"' : ''; ?>>
                                                    <i class="ri-check-line me-1"></i> Approve
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Form submission confirmations
            $('#approve-btn').on('click', function(e) {
                e.preventDefault();
                
                // Check if there's a warning about negative agency fee
                const hasWarning = $(this).data('warning') === true;
                let message = "Are you sure you want to approve this All-In amount?";
                let icon = "question";
                
                if (hasWarning) {
                    message = "Warning: This will result in a negative Agency Fee. Are you sure you want to approve anyway?";
                    icon = "warning";
                }
                
                Swal.fire({
                    title: 'Confirm Approval',
                    text: message,
                    icon: icon,
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, approve it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Submit form with "approve" decision
                        const form = document.getElementById('approval-form');
                        const decisionInput = document.createElement('input');
                        decisionInput.type = 'hidden';
                        decisionInput.name = 'decision';
                        decisionInput.value = 'approve';
                        form.appendChild(decisionInput);
                        form.submit();
                    }
                });
            });
            
            $('#reject-btn').on('click', function(e) {
                e.preventDefault();
                
                Swal.fire({
                    title: 'Confirm Rejection',
                    text: "Are you sure you want to reject this All-In amount?",
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, reject it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Submit form with "reject" decision
                        const form = document.getElementById('approval-form');
                        const decisionInput = document.createElement('input');
                        decisionInput.type = 'hidden';
                        decisionInput.name = 'decision';
                        decisionInput.value = 'reject';
                        form.appendChild(decisionInput);
                        form.submit();
                    }
                });
            });
            
            // Show success message with SweetAlert if present
            <?php if (isset($_SESSION['swal_success'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '<?php echo $_SESSION['swal_success']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_success']); endif; ?>
            
            // Show error message with SweetAlert if present
            <?php if (isset($_SESSION['swal_error'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '<?php echo $_SESSION['swal_error']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_error']); endif; ?>
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>