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

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

// Check if we have a recently created file
if (!isset($_SESSION['created_file_number'])) {
    // No file was created, redirect to the file list
    header('Location: file_list.php');
    exit();
}

// Get the created file information from session
$file_number = $_SESSION['created_file_number'];
$bl = $_SESSION['created_file_bl'] ?? '';

// Get user ID 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'];
} else {
    // Handle the case if user details are not found
    header('Location: login.php');
    exit();
}

// Fetch details about the created file
$sql = "SELECT f.*, c.first_name as customer_name 
        FROM files f 
        LEFT JOIN customers c ON f.customer = c.customer_id 
        WHERE f.file_number = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $file_number);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    // File not found, redirect to file list
    $_SESSION['error_message'] = "File not found.";
    header('Location: file_list.php');
    exit();
}

$file_details = $result->fetch_assoc();

// Fetch the system name
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $system_name = $row['setting_value'];
} else {
    $system_name = "Royal Freight"; // Fallback if not found
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Container Deposit Confirmation')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.css">
    
    <style>
        .card-hover:hover {
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
            transition: all 0.3s ease;
        }
        
        .file-details-card {
            border-left: 3px solid #3498db;
        }
        
        .action-btn {
            min-width: 120px;
        }
    </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' => 'File Management', 'title' => 'Container Deposit Confirmation')); ?>

                    <div class="row">
                        <div class="col-xxl-12">
                            <div class="card file-details-card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">File Creation Successful</h4>
                                </div><!-- end card header -->

                                <div class="card-body">
                                    <div class="alert alert-success" role="alert">
                                        <h5 class="alert-heading">File Created Successfully!</h5>
                                        <p class="mb-0">File Number: <strong><?php echo htmlspecialchars($file_number); ?></strong></p>
                                    </div>
                                    
                                    <div class="row mb-4">
                                        <div class="col-md-6">
                                            <h5 class="text-muted mb-3">File Information</h5>
                                            <div class="table-responsive">
                                                <table class="table table-borderless mb-0">
                                                    <tbody>
                                                        <tr>
                                                            <th scope="row" width="200">File Number:</th>
                                                            <td><?php echo htmlspecialchars($file_number); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th scope="row">Customer:</th>
                                                            <td><?php echo htmlspecialchars($file_details['customer_name'] ?? 'N/A'); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th scope="row">Bill of Lading:</th>
                                                            <td><?php echo htmlspecialchars($file_details['obl_no'] ?? 'N/A'); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th scope="row">Consignee:</th>
                                                            <td><?php echo htmlspecialchars($file_details['consignee_name'] ?? 'N/A'); ?></td>
                                                        </tr>
                                                        <tr>
                                                            <th scope="row">Type:</th>
                                                            <td><?php echo ($file_details['local/transit'] == 1) ? 'Local Shipment' : 'Transit Shipment'; ?></td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="text-center">
                                        <h5 class="mb-4">Would you like to create a container deposit for this shipment?</h5>
                                        <div class="d-flex justify-content-center gap-3">
                                            <button type="button" id="createDepositBtn" class="btn btn-success action-btn">
                                                <i class="ri-add-circle-line align-middle me-1"></i> Yes, Create Deposit
                                            </button>
                                            <button type="button" id="skipDepositBtn" class="btn btn-secondary action-btn">
                                                <i class="ri-skip-forward-line align-middle me-1"></i> No, Skip
                                            </button>
                                        </div>
                                    </div>
                                </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'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Create Deposit button handler
            document.getElementById('createDepositBtn').addEventListener('click', function() {
                window.location.href = 'container_deposit.php?obl_no=<?php echo urlencode($file_details['obl_no'] ?? ''); ?>';
            });

        // Skip Deposit button handler
        document.getElementById('skipDepositBtn').addEventListener('click', function() {
            Swal.fire({
                title: 'Skip Container Deposit?',
                text: "You can always create a container deposit later.",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, skip',
                cancelButtonText: 'No, go back'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Clear the session variables first
                    fetch('clear_file_session.php')
                        .then(response => {
                            // Redirect to view file page with the file id
                            window.location.href = 'view_file.php?id=<?php echo $file_details['id'] ?? $file_details['file_id'] ?? 0; ?>';
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            // Even on error, redirect to view file page
                            window.location.href = 'view_file.php?id=<?php echo $file_details['id'] ?? $file_details['file_id'] ?? 0; ?>';
                        });
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    // User clicked "No, go back" - redirect to file list
                    window.location.href = 'file_list.php';
                }
            });
        });
        });
    </script>
</body>
</html>