<?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 DISTINCT bl FROM container_deposit WHERE deposit > 0 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'] ?? '';
$shipping_line = '';
$type = '';
$container = '';
$deposit_amount = 0;
$refund_amount = 0;
$balance = 0;
$date_deposited = '';
$refund_date = '';

if (!empty($selected_bl)) {
    // Get container deposit information
    $query_data = "SELECT 
                    shipping_line, 
                    type, 
                    container, 
                    deposit, 
                    date_deposited,
                    refund_amount, 
                    balance,
                    refund_date
                  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()) {
        $shipping_line = $row_data['shipping_line'] ?? '';
        $type = $row_data['type'] ?? '';
        $container = $row_data['container'] ?? '';
        $deposit_amount = $row_data['deposit'] ?? 0;
        $date_deposited = $row_data['date_deposited'] ? date('Y-m-d', strtotime($row_data['date_deposited'])) : '';
        $refund_amount = $row_data['refund_amount'] ?? 0;
        $balance = $row_data['balance'] ?? null;
        $refund_date = $row_data['refund_date'] ? date('Y-m-d', strtotime($row_data['refund_date'])) : '';
    }
    
    // Calculate balance if it's null
    if ($balance === null) {
        $balance = $deposit_amount - $refund_amount;
    }
}

// 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 Deposit Refund')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .required-field::after {
            content: " *";
            color: red;
        }
        .form-control[readonly] {
            background-color: #f8f9fa;
        }
        .currency-input {
            position: relative;
        }
        .currency-input input {
            padding-left: 30px;
        }
        .currency-symbol {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            z-index: 10;
        }
    </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' => 'Deposit Refund 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 Deposit Refund Capture</h4>
                                </div>
                                <div class="card-body">
                                    <!-- BL Selection Form -->
                                    <form method="POST" action="container_deposit_refund.php" id="blSelectionForm">
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <label for="bl" class="form-label required-field">Bill of Lading (BL):</label>
                                                <select class="form-select" id="bl" name="bl" required onchange="this.form.submit()">
                                                    <option value="">Select 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)): ?>
                                    <!-- Deposit Refund Form -->
                                    <form method="POST" action="save_deposit_refund.php" id="depositRefundForm">
                                        <input type="hidden" name="bl" value="<?php echo htmlspecialchars($selected_bl); ?>">
                                        <input type="hidden" name="created_by" value="<?php echo $user_id; ?>">
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="shipping_line" class="form-label">Shipping Line:</label>
                                                <input type="text" class="form-control" id="shipping_line" name="shipping_line" value="<?php echo htmlspecialchars($shipping_line); ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="type" class="form-label">Type:</label>
                                                <input type="text" class="form-control" id="type" name="type" value="<?php echo htmlspecialchars($type); ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="container" class="form-label">Container Number:</label>
                                                <input type="text" class="form-control" id="container" name="container" value="<?php echo htmlspecialchars($container); ?>" readonly>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="date_deposited" class="form-label">Date Deposited:</label>
                                                <input type="date" class="form-control" id="date_deposited" name="date_deposited" value="<?php echo $date_deposited; ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="deposit_amount" class="form-label">Deposit Amount:</label>
                                                <div class="currency-input">
                                                    <span class="currency-symbol">$</span>
                                                    <input type="number" step="0.01" class="form-control" id="deposit_amount" name="deposit_amount" value="<?php echo number_format($deposit_amount, 2, '.', ''); ?>" readonly>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="balance" class="form-label">Current Balance:</label>
                                                <div class="currency-input">
                                                    <span class="currency-symbol">$</span>
                                                    <input type="number" step="0.01" class="form-control" id="balance" name="balance" value="<?php echo number_format($balance, 2, '.', ''); ?>" readonly>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <label for="refund_amount" class="form-label required-field">Refund Amount:</label>
                                                <div class="currency-input">
                                                    <span class="currency-symbol">$</span>
                                                    <input type="number" step="0.01" class="form-control" id="refund_amount" name="refund_amount" value="<?php echo $refund_amount > 0 ? number_format($refund_amount, 2, '.', '') : ''; ?>" required max="<?php echo $balance; ?>">
                                                </div>
                                                <small class="text-muted">Cannot exceed the current balance</small>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="refund_date" class="form-label required-field">Refund Date:</label>
                                                <input type="date" class="form-control" id="refund_date" name="refund_date" value="<?php echo $refund_date; ?>" required>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-4">
                                            <div class="col-md-12">
                                                <label for="remarks" class="form-label">Remarks:</label>
                                                <textarea class="form-control" id="remarks" name="remarks" rows="3"></textarea>
                                            </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" id="saveButton">
                                                        <i class="ri-save-line"></i> Process Refund
                                                    </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') {
            $('#bl').select2({
                placeholder: "Select BL",
                allowClear: true
            });
        }

        // Validate refund amount
        const refundInput = document.getElementById('refund_amount');
        const balanceInput = document.getElementById('balance');
        const saveButton = document.getElementById('saveButton');
        
        if (refundInput && balanceInput) {
            refundInput.addEventListener('input', function() {
                const refundAmount = parseFloat(refundInput.value) || 0;
                const balanceAmount = parseFloat(balanceInput.value) || 0;
                
                if (refundAmount > balanceAmount) {
                    refundInput.setCustomValidity("Refund amount cannot exceed balance");
                    saveButton.disabled = true;
                } else if (refundAmount <= 0) {
                    refundInput.setCustomValidity("Refund amount must be greater than zero");
                    saveButton.disabled = true;
                } else {
                    refundInput.setCustomValidity("");
                    saveButton.disabled = false;
                }
            });
        }
        
        // Add validation to prevent refund date being before deposit date
        const depositDateInput = document.getElementById('date_deposited');
        const refundDateInput = document.getElementById('refund_date');
        
        if (depositDateInput && refundDateInput) {
            refundDateInput.addEventListener('change', function() {
                if (depositDateInput.value && refundDateInput.value) {
                    const depositDate = new Date(depositDateInput.value);
                    const refundDate = new Date(refundDateInput.value);
                    
                    if (refundDate < depositDate) {
                        alert('Refund date cannot be earlier than deposit date');
                        refundDateInput.value = '';
                    }
                }
            });
        }
    });
    </script>
</body>
</html>