<?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();
}

$obl_no = isset($_GET['obl_no']) ? $_GET['obl_no'] : '';

// Query to fetch user details
$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();
}

// Initialize variable for existing remarks
$existing_remarks = "";
$file_number = "";

if (isset($_GET['obl_no']) && !empty($_GET['obl_no'])) {
    $obl_no = $_GET['obl_no'];

    // Query to fetch existing remarks and file number
    $sql = "SELECT file_number FROM files WHERE obl_no = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $obl_no);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $file_number = $row['file_number'];
    }
    $stmt->close();
    
    // Check for existing container deposit
    $sql = "SELECT remarks FROM container_deposit WHERE bl = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $obl_no);
    $stmt->execute();
    $stmt->bind_result($existing_remarks);
    $stmt->fetch();
    $stmt->close();
}

// 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')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .red-text {
            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' => 'Delivery & Returns', 'title' => 'Container Deposits')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Container Deposit Capture</h5>
                                    <div class="col text-end">
                                        <span class="red-text">*</span> Required Fields - Must be Filled
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <form id="container-deposit-form" action="save_container_deposit.php" method="POST">
                                        <div class="row mb-3">
                                            <div class="col-sm-4">
                                                <label class="form-label">Shipping Line <span class="red-text">*</span></label>
                                                <input type="text" class="form-control" name="shipping_line" required>
                                            </div>
                                            <div class="col-sm-4">
                                                <label class="form-label">Type <span class="red-text">*</span></label>
                                                <select class="form-select" name="type" id="type_select" required>
                                                    <option value="normal">Cash</option>
                                                    <option value="fixed">Fixed</option>
                                                    <option value="additional">Additional</option>
                                                </select>
                                            </div>
                                            <div class="col-sm-4">
                                                <label class="form-label">Bill of Lading (BL)</label>
                                                <div class="input-group">
                                                    <input type="text" class="form-control" name="bl" value="<?php echo htmlspecialchars($obl_no); ?>" readonly>
                                                    <span class="input-group-text"><?php echo htmlspecialchars($file_number); ?></span>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-sm-4">
                                                <label class="form-label">Date Deposited</label>
                                                <input type="date" class="form-control" name="date">
                                            </div>
                                            <div class="col-sm-4">
                                                <label class="form-label">Container Number</label>
                                                <input type="text" class="form-control" name="container">
                                            </div>
                                            <div class="col-sm-4" id="fixed_amount_field" style="display:none;">
                                                <label class="form-label">Fixed Amount</label>
                                                <input type="number" step="0.01" class="form-control" name="fixed_amount">
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-sm-4" id="deposit_amount_field">
                                                <label class="form-label">Deposit Amount</label>
                                                <input type="number" step="0.01" class="form-control" name="deposit" id="deposit_amount">
                                            </div>
                                            <div class="col-sm-8">
                                                <label class="form-label">Remarks</label>
                                                <textarea class="form-control" name="remarks" rows="1"><?php echo htmlspecialchars($existing_remarks); ?></textarea>
                                            </div>
                                        </div>
                                        
                                        <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
                                        <div class="row mt-4">
                                            <div class="col-12">
                                                <button type="submit" class="btn btn-success">
                                                    <i class="ri-save-line align-middle me-1"></i> Save
                                                </button>
                                                <a href="file_list.php" class="btn btn-danger">
                                                    <i class="ri-close-line align-middle me-1"></i> Cancel
                                                </a>
                                            </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'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            // Get the dropdown and fields
            const typeSelect = document.getElementById('type_select');
            const fixedAmountField = document.getElementById('fixed_amount_field');
            const depositAmountField = document.getElementById('deposit_amount_field');

            // Function to toggle the fields based on the type selected
            function toggleFields() {
                const selectedType = typeSelect.value;

                if (selectedType === 'fixed') {
                    depositAmountField.style.display = 'none'; // Hide deposit amount
                    fixedAmountField.style.display = 'block'; // Show fixed amount
                } else if (selectedType === 'normal') {
                    fixedAmountField.style.display = 'none'; // Hide fixed amount
                    depositAmountField.style.display = 'block'; // Show deposit amount
                } else {
                    // For 'additional' or other types, show both
                    fixedAmountField.style.display = 'block';
                    depositAmountField.style.display = 'block';
                }
            }

            // Initialize the form with the correct fields
            toggleFields();

            // Add event listener to toggle fields when the type is changed
            typeSelect.addEventListener('change', toggleFields);
        });
    </script>
</body>
</html>