<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Verify it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method";
    header('Location: trans_reassign.php');
    exit();
}

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

// Validate required fields
$required_fields = ['file_number', 'container_code', 'new_transporter', 'driver_name', 'driver_phone', 'driver_license', 'reason'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field]) || empty($_POST[$field])) {
        $_SESSION['error_message'] = "Missing required field: $field";
        header('Location: trans_reassign.php');
        exit();
    }
}

// Get form data
$file_number = $_POST['file_number'];
$container_code = $_POST['container_code'];
$new_transporter_id = $_POST['new_transporter'];
$driver_name = $_POST['driver_name'];
$driver_phone = $_POST['driver_phone'];
$driver_license = $_POST['driver_license'];
$reason = $_POST['reason'];

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get the new transporter name
    $transporter_query = "SELECT name FROM transporter_info WHERE id = ?";
    $transporter_stmt = $conn->prepare($transporter_query);
    $transporter_stmt->bind_param('i', $new_transporter_id);
    $transporter_stmt->execute();
    $transporter_result = $transporter_stmt->get_result();
    
    if ($transporter_result->num_rows === 0) {
        throw new Exception("Invalid transporter selected");
    }
    
    $transporter_row = $transporter_result->fetch_assoc();
    $new_transporter_name = $transporter_row['name'];
    
    // Get the current transporter name for history
    $current_query = "SELECT transporter_name FROM container_details WHERE file_number = ? AND container_code = ?";
    $current_stmt = $conn->prepare($current_query);
    $current_stmt->bind_param('ss', $file_number, $container_code);
    $current_stmt->execute();
    $current_result = $current_stmt->get_result();
    
    if ($current_result->num_rows === 0) {
        throw new Exception("Container not found");
    }
    
    $current_row = $current_result->fetch_assoc();
    $old_transporter_name = $current_row['transporter_name'];
    
    // Update the container details
    $update_query = "UPDATE container_details 
                    SET transporter_name = ?, 
                        driver_name = ?, 
                        driver_phone_number = ?, 
                        driver_license = ? 
                    WHERE file_number = ? AND container_code = ?";
                    
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param('ssssss', 
        $new_transporter_name, 
        $driver_name, 
        $driver_phone, 
        $driver_license, 
        $file_number, 
        $container_code
    );
    
    if (!$update_stmt->execute()) {
        throw new Exception("Failed to update container details: " . $update_stmt->error);
    }
    
    // Check if truck_reassignments table exists, and if not, create it
    $check_table = $conn->query("SHOW TABLES LIKE 'truck_reassignments'");
    if ($check_table->num_rows == 0) {
        // Create the truck_reassignments table
        $create_table = "CREATE TABLE IF NOT EXISTS `truck_reassignments` (
          `id` int NOT NULL AUTO_INCREMENT,
          `file_number` varchar(50) NOT NULL,
          `container_code` varchar(50) NOT NULL,
          `old_transporter` varchar(100) NOT NULL,
          `new_transporter` varchar(100) NOT NULL,
          `reassigned_by` int NOT NULL,
          `reason` text NOT NULL,
          `reassignment_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
          PRIMARY KEY (`id`),
          KEY `file_number` (`file_number`),
          KEY `reassigned_by` (`reassigned_by`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
        
        $conn->query($create_table);
    }
    
    // Log the reassignment in history table
    $log_query = "INSERT INTO truck_reassignments (
                    file_number, 
                    container_code, 
                    old_transporter, 
                    new_transporter, 
                    reassigned_by, 
                    reason, 
                    reassignment_date
                  ) VALUES (?, ?, ?, ?, ?, ?, NOW())";
                  
    $log_stmt = $conn->prepare($log_query);
    $log_stmt->bind_param('ssssss', 
        $file_number, 
        $container_code, 
        $old_transporter_name, 
        $new_transporter_name, 
        $user_id, 
        $reason
    );
    
    $log_stmt->execute();
    
    // Create a notification about the change
    $notif_message = "Container $container_code in file $file_number reassigned from $old_transporter_name to $new_transporter_name";
    
    // Get the file ID for the notification
    $file_id_query = "SELECT id FROM files WHERE file_number = ?";
    $file_id_stmt = $conn->prepare($file_id_query);
    $file_id_stmt->bind_param('s', $file_number);
    $file_id_stmt->execute();
    $file_id_result = $file_id_stmt->get_result();
    
    if ($file_id_result->num_rows > 0) {
        $file_id_row = $file_id_result->fetch_assoc();
        $file_id = $file_id_row['id'];
        
        $notif_query = "INSERT INTO notifications (
                            file_id, 
                            file_number, 
                            notif_message, 
                            notif_message_id, 
                            created_at
                         ) VALUES (?, ?, ?, 2, NOW())";
                         
        $notif_stmt = $conn->prepare($notif_query);
        $notif_stmt->bind_param('iss', $file_id, $file_number, $notif_message);
        $notif_stmt->execute();
    }
    
    // Commit the transaction
    $conn->commit();
    
    $_SESSION['success_message'] = "Truck reassignment completed successfully";
    header('Location: truck_reassignments.php');
    exit();
    
} catch (Exception $e) {
    // Rollback the transaction on error
    $conn->rollback();
    
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: truck_reassignments.php');
    exit();
}
?>