<?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 BL numbers from container_deposit table
$query_bl = "SELECT bl FROM container_deposit GROUP BY bl ORDER BY bl";
$result_bl = $conn->query($query_bl);
$bl_numbers = [];
if ($result_bl && $result_bl->num_rows > 0) {
    while ($row = $result_bl->fetch_assoc()) {
        $bl_numbers[] = $row['bl'];
    }
}

// Get existing data if BL is selected
$selected_bl = $_POST['bl'] ?? '';
$existing_remarks = '';
$existing_deposit_roll_over = '';
$existing_additional_info = '';

if (!empty($selected_bl)) {
    $query_data = "SELECT remarks, deposit_roll_over, additional_info FROM container_deposit 
                  WHERE bl = ? ORDER BY id DESC LIMIT 1";
    $stmt = $conn->prepare($query_data);
    $stmt->bind_param("s", $selected_bl);
    $stmt->execute();
    $result_data = $stmt->get_result();
    
    if ($row_data = $result_data->fetch_assoc()) {
        $existing_remarks = $row_data['remarks'] ?? '';
        $existing_deposit_roll_over = $row_data['deposit_roll_over'] ?? '';
        $existing_additional_info = $row_data['additional_info'] ?? '';
    }
}

// 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' => 'Update Container Deposit Remarks')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .required-field::after {
            content: " *";
            color: red;
        }
    </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 Deposit', 'title' => 'Update Remarks')); ?>

                    <!-- 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 Deposit Remarks Update</h4>
                                </div>
                                <div class="card-body">
                                    <!-- BL Selection Form -->
                                    <form method="POST" action="update_container_remarks.php" id="blSelectionForm">
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <label for="bl" class="form-label required-field">BL No:</label>
                                                <select class="form-select" id="bl" name="bl" required onchange="this.form.submit()">
                                                    <option value="">Please Select A BL</option>
                                                    <?php foreach ($bl_numbers as $bl): ?>
                                                        <option value="<?php echo htmlspecialchars($bl); ?>" <?php echo ($selected_bl === $bl) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($bl); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </form>

                                    <?php if (!empty($selected_bl)): ?>
                                    <!-- Remarks Update Form -->
                                    <form method="POST" action="save_container_remarks.php" id="remarksUpdateForm">
                                        <input type="hidden" name="bl" value="<?php echo htmlspecialchars($selected_bl); ?>">
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="existingRemarks" class="form-label">Existing Remarks:</label>
                                                <div class="card">
                                                    <div class="card-body bg-light" style="max-height: 200px; overflow-y: auto;">
                                                        <pre style="white-space: pre-wrap; margin-bottom: 0;"><?php echo htmlspecialchars($existing_remarks); ?></pre>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="existingRollOver" class="form-label">Deposit Roll Over:</label>
                                                <div class="card">
                                                    <div class="card-body bg-light" style="max-height: 200px; overflow-y: auto;">
                                                        <pre style="white-space: pre-wrap; margin-bottom: 0;"><?php echo htmlspecialchars($existing_deposit_roll_over); ?></pre>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="existingAdditionalInfo" class="form-label">Additional Info:</label>
                                                <div class="card">
                                                    <div class="card-body bg-light" style="max-height: 200px; overflow-y: auto;">
                                                        <pre style="white-space: pre-wrap; margin-bottom: 0;"><?php echo htmlspecialchars($existing_additional_info); ?></pre>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-4">
                                            <div class="col-md-4">
                                                <label for="newRemarks" class="form-label">New Remarks:</label>
                                                <textarea class="form-control" id="newRemarks" name="new_remarks" rows="5" placeholder="Enter new remarks"></textarea>
                                                <small class="text-muted">Enter additional remarks here</small>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="newRollOver" class="form-label">New Deposit Roll Over:</label>
                                                <textarea class="form-control" id="newRollOver" name="new_roll_over" rows="5" placeholder="Enter new Deposit Roll Over details"></textarea>
                                                <small class="text-muted">Enter additional Deposit Roll Over details here</small>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="newAdditionalInfo" class="form-label">New Additional Info:</label>
                                                <textarea class="form-control" id="newAdditionalInfo" name="new_additional_info" rows="5" placeholder="Enter new Additional info"></textarea>
                                                <small class="text-muted">Enter additional info here</small>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-12">
                                                <div class="d-flex justify-content-start">
                                                    <a href="container_depo_list.php" class="btn btn-secondary me-2">
                                                        <i class="ri-arrow-left-line"></i> Back to List
                                                    </a>
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-save-line"></i> Save Changes
                                                    </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>
</body>
</html>