<?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: delivery_returns.php');
    exit();
}

// Get user ID for tracking
$user_id = $_SESSION['user_id'];

// Collect form data
$file_number = isset($_POST['file_number']) ? trim($_POST['file_number']) : '';
$bl = isset($_POST['bl']) ? trim($_POST['bl']) : '';
$container_no = isset($_POST['container_no']) ? trim($_POST['container_no']) : '';
$load_date = !empty($_POST['load_date']) ? date('Y-m-d', strtotime($_POST['load_date'])) : null;
$return_date = !empty($_POST['return_date']) ? date('Y-m-d', strtotime($_POST['return_date'])) : null;

// For debugging
error_log("Processing delivery & returns for file: $file_number");
error_log("Container No: $container_no, Load Date: $load_date, Return Date: $return_date");

// Validation
if (empty($file_number)) {
    $_SESSION['error_message'] = "File number is required.";
    header('Location: delivery_returns.php');
    exit();
}

if (empty($container_no)) {
    $_SESSION['error_message'] = "Container number is required.";
    header('Location: delivery_returns.php');
    exit();
}

if (empty($load_date)) {
    $_SESSION['error_message'] = "Loading date is required.";
    header('Location: delivery_returns.php');
    exit();
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Check if there's already a record for this file number
    $check_query = "SELECT id FROM delivery_returns WHERE file_number = ?";
    $check_stmt = $conn->prepare($check_query);
    $check_stmt->bind_param("s", $file_number);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows > 0) {
        // Update existing record
        $update_sql = "UPDATE delivery_returns 
                      SET bl = ?, container_no = ?, load_date = ?, return_date = ? 
                      WHERE file_number = ?";
        
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("sssss", $bl, $container_no, $load_date, $return_date, $file_number);
        
        if (!$stmt->execute()) {
            throw new Exception("Error updating delivery & returns: " . $stmt->error);
        }
        
        $message = "Container delivery & returns information updated successfully.";
    } else {
        // Insert new record
        $insert_sql = "INSERT INTO delivery_returns 
                      (file_number, user_id, bl, container_no, load_date, return_date, created_date) 
                      VALUES (?, ?, ?, ?, ?, ?, NOW())";
        
        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param("sissss", $file_number, $user_id, $bl, $container_no, $load_date, $return_date);
        
        if (!$stmt->execute()) {
            throw new Exception("Error saving delivery & returns: " . $stmt->error);
        }
        
        $message = "Container delivery & returns information saved successfully.";
    }
    
    // Also update the files table with load_date and offload_date
    $update_files_sql = "UPDATE files 
                        SET load_date = ?, offload_date = ? 
                        WHERE file_number = ?";
    
    $files_stmt = $conn->prepare($update_files_sql);
    $files_stmt->bind_param("sss", $load_date, $return_date, $file_number);
    $files_stmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    // Success - set session message
    $_SESSION['success_message'] = $message;
    
    // Redirect back
    header('Location: delivery_returns.php');
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log the error
    error_log("Error saving delivery & returns: " . $e->getMessage());
    
    // Show error message
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: delivery_returns.php');
    exit();
}
?>