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

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

// Get user details
$stmt = $conn->prepare("SELECT username FROM users WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
    $username = $row['username'];
}
$stmt->close();

// Collect form data
$bl = isset($_POST['bl']) ? trim($_POST['bl']) : '';
$new_remarks = isset($_POST['new_remarks']) ? trim($_POST['new_remarks']) : '';
$new_roll_over = isset($_POST['new_roll_over']) ? trim($_POST['new_roll_over']) : '';
$new_additional_info = isset($_POST['new_additional_info']) ? trim($_POST['new_additional_info']) : '';

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

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get existing data
    $query_data = "SELECT remarks, deposit_roll_over, additional_info FROM container_deposit 
                  WHERE bl = ? ORDER BY id DESC LIMIT 1";
    $stmt = $conn->prepare($query_data);
    $stmt->bind_param("s", $bl);
    $stmt->execute();
    $result_data = $stmt->get_result();
    
    $existing_remarks = '';
    $existing_deposit_roll_over = '';
    $existing_additional_info = '';
    
    if ($row_data = $result_data->fetch_assoc()) {
        $existing_remarks = $row_data['remarks'] ?? '';
        $existing_deposit_roll_over = $row_data['deposit_roll_over'] ?? '';
        $existing_additional_info = $row_data['additional_info'] ?? '';
    }
    $stmt->close();
    
    // Prepare updated values
    $current_date = date('Y-m-d');
    $user_signature = " - " . $username . " on " . $current_date;
    
    // Only append to existing if new content is provided
    $updated_remarks = $existing_remarks;
    if (!empty($new_remarks)) {
        // If there's existing remarks, preserve them and add a line break
        $updated_remarks = ($updated_remarks ? $updated_remarks . "\n" : '');
        // Add the new remarks with user signature
        $updated_remarks .= $new_remarks . $user_signature;
    }
    
    $updated_roll_over = $existing_deposit_roll_over;
    if (!empty($new_roll_over)) {
        // Preserve existing roll-over info
        $updated_roll_over = ($updated_roll_over ? $updated_roll_over . "\n" : '');
        // Add new roll-over info with user signature
        $updated_roll_over .= $new_roll_over . $user_signature;
    }
    
    $updated_additional_info = $existing_additional_info;
    if (!empty($new_additional_info)) {
        // Preserve existing additional info
        $updated_additional_info = ($updated_additional_info ? $updated_additional_info . "\n" : '');
        // Add new additional info with user signature
        $updated_additional_info .= $new_additional_info . $user_signature;
    }
    
    // Check if anything changed
    if ($updated_remarks === $existing_remarks && 
        $updated_roll_over === $existing_deposit_roll_over && 
        $updated_additional_info === $existing_additional_info) {
        $_SESSION['error_message'] = "No changes were made.";
        header('Location: update_container_remarks.php');
        exit();
    }
    
    // Update the latest container deposit record
    $update_sql = "UPDATE container_deposit 
                  SET remarks = ?, deposit_roll_over = ?, additional_info = ? 
                  WHERE bl = ? AND id = (SELECT max_id FROM (SELECT MAX(id) as max_id FROM container_deposit WHERE bl = ?) as temp)";
                  
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("sssss", $updated_remarks, $updated_roll_over, $updated_additional_info, $bl, $bl);
    
    if (!$stmt->execute()) {
        throw new Exception("Error updating container deposit remarks: " . $stmt->error);
    }
    
    // Check if any rows were affected
    if ($stmt->affected_rows == 0) {
        throw new Exception("No records were updated. The BL might not exist or you might not have permission to update it.");
    }
    
    // Commit transaction
    $conn->commit();
    
    // Success - set session message
    $_SESSION['success_message'] = "Container deposit remarks updated successfully.";
    
    // Redirect back
    header('Location: update_container_remarks.php');
    exit();
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    // Log the error
    error_log("Error updating container deposit remarks: " . $e->getMessage());
    
    // Show error message
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    header('Location: update_container_remarks.php');
    exit();
}
?>