<?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
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email 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'];
} else {
    // Handle the case if user details are not found
}

// Fetch file numbers for dropdown
$query_files = "SELECT DISTINCT file_number FROM files ORDER BY file_number DESC";
$result_files = $conn->query($query_files);
$file_numbers = [];
if ($result_files && $result_files->num_rows > 0) {
    while ($row = $result_files->fetch_assoc()) {
        $file_numbers[] = $row['file_number'];
    }
}

// Get existing data if file number is selected
$selected_file = isset($_POST['file_number']) ? $_POST['file_number'] : '';
$consignee_name = '';
$destination = '';
$bl = '';
$container_no = '';
$load_date = '';
$return_date = '';

if (!empty($selected_file)) {
    // Get file information
    $query_file = "SELECT f.consignee_name, f.destination, f.obl_no 
                  FROM files f 
                  WHERE f.file_number = ?";
    $stmt = $conn->prepare($query_file);
    $stmt->bind_param("s", $selected_file);
    $stmt->execute();
    $result_file = $stmt->get_result();
    
    if ($row_file = $result_file->fetch_assoc()) {
        $consignee_name = $row_file['consignee_name'] ?? '';
        $destination = $row_file['destination'] ?? '';
        $bl = $row_file['obl_no'] ?? '';
    }
    $stmt->close();
    
    // Check if there's existing delivery return data
    $query_delivery = "SELECT dr.container_no, dr.load_date, dr.return_date 
                      FROM delivery_returns dr 
                      WHERE dr.file_number = ?";
    $stmt = $conn->prepare($query_delivery);
    $stmt->bind_param("s", $selected_file);
    $stmt->execute();
    $result_delivery = $stmt->get_result();
    
    if ($row_delivery = $result_delivery->fetch_assoc()) {
        $container_no = $row_delivery['container_no'] ?? '';
        $load_date = $row_delivery['load_date'] ? date('Y-m-d', strtotime($row_delivery['load_date'])) : '';
        $return_date = $row_delivery['return_date'] ? date('Y-m-d', strtotime($row_delivery['return_date'])) : '';
    }
    $stmt->close();
    
    // If no existing container number, try to get it from container_details
    if (empty($container_no)) {
        $query_container = "SELECT GROUP_CONCAT(container_code SEPARATOR ', ') as containers 
                          FROM container_details 
                          WHERE file_number = ?";
        $stmt = $conn->prepare($query_container);
        $stmt->bind_param("s", $selected_file);
        $stmt->execute();
        $result_container = $stmt->get_result();
        
        if ($row_container = $result_container->fetch_assoc()) {
            $container_no = $row_container['containers'] ?? '';
        }
        $stmt->close();
    }
}

// Set system name from settings
$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
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Container Delivery & Returns')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .required-field::after {
            content: " *";
            color: red;
        }
        .form-control[readonly] {
            background-color: #f8f9fa;
        }
    </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' => 'Container Management', 'title' => 'Delivery & Returns Capture')); ?>

                    <!-- Alert for messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Container Delivery & Returns Capture</h4>
                                </div>
                                <div class="card-body">
                                    <!-- File Selection Form -->
                                    <form method="POST" action="delivery_returns.php" id="fileSelectionForm">
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <label for="file_number" class="form-label required-field">Job No:</label>
                                                <select class="form-select" id="file_number" name="file_number" required onchange="this.form.submit()">
                                                    <option value="">Please Select A Job Number</option>
                                                    <?php foreach ($file_numbers as $file): ?>
                                                        <option value="<?php echo htmlspecialchars($file); ?>" <?php echo ($selected_file === $file) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($file); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </form>

                                    <?php if (!empty($selected_file)): ?>
                                    <!-- Delivery & Returns Form -->
                                    <form method="POST" action="save_delivery_returns.php" id="deliveryReturnsForm">
                                        <input type="hidden" name="file_number" value="<?php echo htmlspecialchars($selected_file); ?>">
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="consignee_name" class="form-label">Consignee Name:</label>
                                                <input type="text" class="form-control" id="consignee_name" name="consignee_name" value="<?php echo htmlspecialchars($consignee_name); ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="destination" class="form-label">Destination:</label>
                                                <input type="text" class="form-control" id="destination" name="destination" value="<?php echo htmlspecialchars($destination); ?>" readonly>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="bl" class="form-label">Bill of Lading (BL):</label>
                                                <input type="text" class="form-control" id="bl" name="bl" value="<?php echo htmlspecialchars($bl); ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="container_no" class="form-label required-field">Container Code:</label>
                                                <input type="text" class="form-control" id="container_no" name="container_no" value="<?php echo htmlspecialchars($container_no); ?>" required>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <label for="load_date" class="form-label required-field">Loading Date:</label>
                                                <input type="date" class="form-control" id="load_date" name="load_date" value="<?php echo $load_date; ?>" required>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="return_date" class="form-label">Return Date:</label>
                                                <input type="date" class="form-control" id="return_date" name="return_date" value="<?php echo $return_date; ?>">
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-12">
                                                <div class="d-flex justify-content-start">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-save-line"></i> Save Information
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                    <?php endif; ?>
                                </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'; ?>

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

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Select2 for better dropdown experience if available
        if (typeof $.fn.select2 !== 'undefined') {
            $('#file_number').select2({
                placeholder: "Please Select A Job Number",
                allowClear: true
            });
        }

        // Add validation to prevent return date being before load date
        const loadDateInput = document.getElementById('load_date');
        const returnDateInput = document.getElementById('return_date');
        
        if (loadDateInput && returnDateInput) {
            returnDateInput.addEventListener('change', function() {
                if (loadDateInput.value && returnDateInput.value) {
                    const loadDate = new Date(loadDateInput.value);
                    const returnDate = new Date(returnDateInput.value);
                    
                    if (returnDate < loadDate) {
                        alert('Return date cannot be earlier than loading date');
                        returnDateInput.value = '';
                    }
                }
            });
        }
    });
    </script>
</body>
</html>