<?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 case if user details are not found
    $_SESSION['error_message'] = "Failed to retrieve user details.";
    header('Location: container_depo_list.php');
    exit();
}

// Check if deposit ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = "Invalid deposit ID provided.";
    header('Location: container_depo_list.php');
    exit();
}

$deposit_id = intval($_GET['id']);

// Fetch the deposit details
$query = "SELECT * FROM container_deposit WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $deposit_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    $deposit = $result->fetch_assoc();
} else {
    $_SESSION['error_message'] = "Container deposit not found.";
    header('Location: container_depo_list.php');
    exit();
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Extract and sanitize form data
    $shipping_line = trim($_POST['shipping_line']);
    $type = trim($_POST['type']);
    $bl = trim($_POST['bl']);
    $container = isset($_POST['container']) ? trim($_POST['container']) : null;
    $deposit_date = !empty($_POST['deposit_date']) ? $_POST['deposit_date'] : null;
    $issue_date = !empty($_POST['issue_date']) ? $_POST['issue_date'] : null;
    $fixed_amount = isset($_POST['fixed_amount']) ? floatval($_POST['fixed_amount']) : null;
    $deposit_amount = isset($_POST['deposit_amount']) ? floatval($_POST['deposit_amount']) : null;
    $refund_amount = isset($_POST['refund_amount']) ? floatval($_POST['refund_amount']) : null;
    $refund_date = !empty($_POST['refund_date']) ? $_POST['refund_date'] : null;
    //$remarks = isset($_POST['remarks']) ? trim($_POST['remarks']) : '';
    $deposit_roll_over = isset($_POST['deposit_roll_over']) ? trim($_POST['deposit_roll_over']) : null;
    $payment_status = isset($_POST['payment_status']) ? trim($_POST['payment_status']) : null;
    $additional_info = isset($_POST['additional_info']) ? trim($_POST['additional_info']) : null;
    
    // Start with existing remarks to preserve them
    $remarks = isset($deposit['remarks']) ? $deposit['remarks'] : '';
    
    // Calculate balance
    $balance = null;
    if ($type === 'fixed') {
        if (!empty($fixed_amount)) {
            $balance = $fixed_amount - ($refund_amount ?? 0);
        }
    } else {
        if (!empty($deposit_amount)) {
            $balance = $deposit_amount - ($refund_amount ?? 0);
        }
    }
    
    // Create new remarks entry with timestamp and username
    $new_remark = '';
    if (!empty($_POST['new_remark'])) {
        $new_remark = " - " . $username . " on " . date('Y-m-d');
        if (!empty($remarks)) {
            $remarks .= "\n" . trim($_POST['new_remark']) . $new_remark;
        } else {
            $remarks = trim($_POST['new_remark']) . $new_remark;
        }
    }
    
    // Update the deposit record
    $update_query = "UPDATE container_deposit SET 
                    shipping_line = ?, 
                    type = ?, 
                    bl = ?, 
                    container = ?, 
                    date = ?, 
                    fixed_amount = ?, 
                    deposit = ?, 
                    date_deposited = ?, 
                    refund_amount = ?, 
                    balance = ?, 
                    refund_date = ?, 
                    remarks = ?, 
                    deposit_roll_over = ?, 
                    payment_status = ?, 
                    additional_info = ? 
                    WHERE id = ?";
                    
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param('sssssddsddsssssi', 
                            $shipping_line, 
                            $type, 
                            $bl, 
                            $container, 
                            $issue_date, 
                            $fixed_amount, 
                            $deposit_amount, 
                            $deposit_date, 
                            $refund_amount, 
                            $balance, 
                            $refund_date, 
                            $remarks, 
                            $deposit_roll_over, 
                            $payment_status, 
                            $additional_info, 
                            $deposit_id);
    
    if ($update_stmt->execute()) {
        $_SESSION['success_message'] = "Container deposit updated successfully.";
        header('Location: container_depo_list.php');
        exit();
    } else {
        $_SESSION['error_message'] = "Failed to update container deposit: " . $conn->error;
    }
    
    $update_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' => 'Edit Container Deposit')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .required-field::after {
            content: "*";
            color: red;
            margin-left: 4px;
        }
        
        .card {
            border-top: 3px solid #3498db;
        }
        
        .remarks-history {
            max-height: 150px;
            overflow-y: auto;
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        
        .type-badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 4px;
            margin-right: 8px;
            cursor: pointer;
        }
        
        .type-badge.active {
            box-shadow: 0 0 0 2px #fff, 0 0 0 4px #3498db;
        }
        
        .badge-normal {
            background-color: #28a745;
            color: white;
        }
        
        .badge-fixed {
            background-color: #6c757d;
            color: white;
        }
        
        .badge-additional {
            background-color: #007bff;
            color: white;
        }
    </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' => 'Edit Deposit')); ?>

                    <!-- Alert for messages -->
                    <?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 d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Edit Container Deposit</h4>
                                    <a href="container_depo_list.php" class="btn btn-sm btn-primary">
                                        <i class="ri-arrow-left-line"></i> Back to Deposit List
                                    </a>
                                </div>
                                <div class="card-body">
                                    <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?id=' . $deposit_id); ?>" method="POST" id="depositForm">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label required-field">Shipping Line</label>
                                                    <input type="text" class="form-control" name="shipping_line" value="<?php echo htmlspecialchars($deposit['shipping_line']); ?>" required>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label required-field">Deposit Type</label>
                                                    <div>
                                                        <div class="type-badge badge-normal <?php echo $deposit['type'] === 'normal' ? 'active' : ''; ?>" data-type="normal">Normal</div>
                                                        <div class="type-badge badge-fixed <?php echo $deposit['type'] === 'fixed' ? 'active' : ''; ?>" data-type="fixed">Fixed</div>
                                                        <div class="type-badge badge-additional <?php echo $deposit['type'] === 'additional' ? 'active' : ''; ?>" data-type="additional">Additional</div>
                                                        <input type="hidden" name="type" id="deposit-type" value="<?php echo htmlspecialchars($deposit['type']); ?>" required>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label required-field">Bill of Lading (BL)</label>
                                                    <input type="text" class="form-control" name="bl" value="<?php echo htmlspecialchars($deposit['bl']); ?>" >
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label">Container</label>
                                                    <input type="text" class="form-control" name="container" value="<?php echo htmlspecialchars($deposit['container'] ?? ''); ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Issue Date</label>
                                                    <input type="date" class="form-control" name="issue_date" value="<?php echo !empty($deposit['date']) ? date('Y-m-d', strtotime($deposit['date'])) : ''; ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Deposit Date</label>
                                                    <input type="date" class="form-control" name="deposit_date" value="<?php echo !empty($deposit['date_deposited']) ? date('Y-m-d', strtotime($deposit['date_deposited'])) : ''; ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 amount-field" id="fixed-amount-field" style="<?php echo $deposit['type'] === 'fixed' ? '' : 'display: none;'; ?>">
                                                <div class="mb-3">
                                                    <label class="form-label required-field">Fixed Amount</label>
                                                    <div class="input-group">
                                                        <span class="input-group-text">$</span>
                                                        <input type="number" class="form-control" name="fixed_amount" step="0.01" min="0" value="<?php echo htmlspecialchars($deposit['fixed_amount'] ?? '0.00'); ?>">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 amount-field" id="deposit-amount-field" style="<?php echo $deposit['type'] !== 'fixed' ? '' : 'display: none;'; ?>">
                                                <div class="mb-3">
                                                    <label class="form-label required-field">Deposit Amount</label>
                                                    <div class="input-group">
                                                        <span class="input-group-text">$</span>
                                                        <input type="number" class="form-control" name="deposit_amount" step="0.01" min="0" value="<?php echo htmlspecialchars($deposit['deposit'] ?? '0.00'); ?>">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Refund Amount</label>
                                                    <div class="input-group">
                                                        <span class="input-group-text">$</span>
                                                        <input type="number" class="form-control" name="refund_amount" step="0.01" min="0" value="<?php echo htmlspecialchars($deposit['refund_amount'] ?? '0.00'); ?>">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Refund Date</label>
                                                    <input type="date" class="form-control" name="refund_date" value="<?php echo !empty($deposit['refund_date']) ? date('Y-m-d', strtotime($deposit['refund_date'])) : ''; ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Payment Status</label>
                                                    <select class="form-select" name="payment_status">
                                                        <option value="" <?php echo empty($deposit['payment_status']) ? 'selected' : ''; ?>>N/A</option>
                                                        <option value="Pending" <?php echo $deposit['payment_status'] === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                                        <option value="Approved" <?php echo $deposit['payment_status'] === 'Approved' ? 'selected' : ''; ?>>Approved</option>
                                                        <option value="Rejected" <?php echo $deposit['payment_status'] === 'Rejected' ? 'selected' : ''; ?>>Rejected</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label">Deposit Roll Over</label>
                                                    <input type="text" class="form-control" name="deposit_roll_over" value="<?php echo htmlspecialchars($deposit['deposit_roll_over'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label class="form-label">Additional Information</label>
                                                    <input type="text" class="form-control" name="additional_info" value="<?php echo htmlspecialchars($deposit['additional_info'] ?? ''); ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="mb-3">
                                                    <label class="form-label">Remarks History</label>
                                                    <?php if (!empty($deposit['remarks'])): ?>
                                                    <div class="remarks-history">
                                                        <?php echo nl2br(htmlspecialchars($deposit['remarks'])); ?>
                                                    </div>
                                                    <?php else: ?>
                                                    <div class="alert alert-secondary">No remarks history available</div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="mb-3">
                                                    <label class="form-label">Add New Remark</label>
                                                    <textarea class="form-control" name="new_remark" rows="3" placeholder="Add a new remark..."></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mt-3">
                                            <div class="col-md-12 d-flex justify-content-between">
                                                <a href="container_depo_list.php" class="btn btn-danger">
                                                    <i class="ri-close-line"></i> Cancel
                                                </a>
                                                <button type="submit" class="btn btn-success">
                                                    <i class="ri-save-line"></i> Save Changes
                                                </button>
                                            </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'; ?>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>

    <script>
    $(document).ready(function() {
        // Handle deposit type selection
        $('.type-badge').on('click', function() {
            const selectedType = $(this).data('type');
            
            // Set the hidden input value
            $('#deposit-type').val(selectedType);
            
            // Toggle active class
            $('.type-badge').removeClass('active');
            $(this).addClass('active');
            
            // Show/hide amount fields based on selected type
            if (selectedType === 'fixed') {
                $('#fixed-amount-field').show();
                $('#deposit-amount-field').hide();
            } else {
                $('#fixed-amount-field').hide();
                $('#deposit-amount-field').show();
            }
        });
        
        // Form validation before submit
        $('#depositForm').on('submit', function(e) {
            const depositType = $('#deposit-type').val();
            let isValid = true;
            
            // Validate required fields
            if (!$('input[name="shipping_line"]').val().trim()) {
                alert('Please enter the shipping line.');
                isValid = false;
            } else if (!$('input[name="bl"]').val().trim()) {
                alert('Please enter the Bill of Lading (BL) number.');
                isValid = false;
            } else if (depositType === 'fixed' && (!$('input[name="fixed_amount"]').val() || parseFloat($('input[name="fixed_amount"]').val()) <= 0)) {
                alert('Please enter a valid fixed amount.');
                isValid = false;
            } else if (depositType !== 'fixed' && (!$('input[name="deposit_amount"]').val() || parseFloat($('input[name="deposit_amount"]').val()) <= 0)) {
                alert('Please enter a valid deposit amount.');
                isValid = false;
            }
            
            // Validate refund amount if refund date is provided
            if ($('input[name="refund_date"]').val() && (!$('input[name="refund_amount"]').val() || parseFloat($('input[name="refund_amount"]').val()) <= 0)) {
                alert('Please enter a valid refund amount when providing a refund date.');
                isValid = false;
            }
            
            // Validate refund date if refund amount is provided
            if (parseFloat($('input[name="refund_amount"]').val()) > 0 && !$('input[name="refund_date"]').val()) {
                alert('Please provide a refund date when entering a refund amount.');
                isValid = false;
            }
            
            if (!isValid) {
                e.preventDefault();
            }
        });
    });
    </script>
</body>
</html>