<?php
session_start();
include 'layouts/dbconn.php';
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit();
}
// Get user ID for tracking
$user_id = $_POST['user_id'] ?? $_SESSION['user_id'];
// Collect form data with proper validation
$shipping_line = isset($_POST['shipping_line']) ? trim($_POST['shipping_line']) : '';
$type = isset($_POST['type']) ? trim($_POST['type']) : 'normal';
$bl = isset($_POST['bl']) ? trim($_POST['bl']) : '';
$date = !empty($_POST['date']) ? date('Y-m-d', strtotime($_POST['date'])) : null;
$container = isset($_POST['container']) ? trim($_POST['container']) : '';
$fixed_amount = !empty($_POST['fixed_amount']) ? (float)$_POST['fixed_amount'] : 0;
$deposit = !empty($_POST['deposit']) ? (float)$_POST['deposit'] : 0;
$remarks = isset($_POST['remarks']) ? trim($_POST['remarks']) : '';
// Validation
if (empty($shipping_line)) {
    $_SESSION['error_message'] = "Shipping Line is required.";
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit();
}
if (empty($type) || !in_array($type, ['normal', 'fixed', 'additional'])) {
    $_SESSION['error_message'] = "Invalid deposit type.";
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit();
}
try {
    // Start transaction
    $conn->begin_transaction();
    
    // Generate remarks addition with username and date
    $user_query = "SELECT username FROM users WHERE user_id = ?";
    $user_stmt = $conn->prepare($user_query);
    $user_stmt->bind_param('i', $user_id);
    $user_stmt->execute();
    $user_result = $user_stmt->get_result();
    $username = ($user_result->num_rows > 0) ? $user_result->fetch_assoc()['username'] : 'unknown';
    
    $current_date = date('Y-m-d');
    $remarks_addition = " - " . $username . " on " . $current_date;
    
    // Append the new remarks to any existing ones
    $updated_remarks = $remarks . $remarks_addition;
    
    // Insert container deposit record
    $sql = "INSERT INTO container_deposit (
        shipping_line, type, bl, date, container, 
        fixed_amount, deposit, remarks, user_id, created_date
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        'sssssddsi',
        $shipping_line, $type, $bl, $date, $container,
        $fixed_amount, $deposit, $updated_remarks, $user_id
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Error saving container deposit: " . $stmt->error);
    }
    
    // Commit transaction
    $conn->commit();
    
    // Success - clear session variables from file creation if they exist
    if (isset($_SESSION['created_file_number'])) {
        unset($_SESSION['created_file_number']);
    }
    
    if (isset($_SESSION['created_file_bl'])) {
        unset($_SESSION['created_file_bl']);
    }
    
    // Find the related file ID using the bill of lading number
    $file_query = "SELECT id FROM files WHERE obl_no = ?";
    $file_stmt = $conn->prepare($file_query);
    $file_stmt->bind_param('s', $bl);
    $file_stmt->execute();
    $file_result = $file_stmt->get_result();
    
    // Set success message
    $_SESSION['success_message'] = "Container deposit saved successfully.";
    
    // Redirect to view file if file ID is found, otherwise go to deposit list
    if ($file_result->num_rows > 0) {
        $file_id = $file_result->fetch_assoc()['id'];
        header('Location: view_file.php?id=' . $file_id);
    } else {
        header('Location: container_depo_list.php');
    }
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log the error
    error_log("Error saving container deposit: " . $e->getMessage());
    
    // Show error message
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: ' . $_SERVER['HTTP_REFERER']);
    exit();
}
?>