<?php
// admin/add-tracking.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

$shipment_id = intval($_POST['shipment_id'] ?? 0);
$status = sanitize($_POST['status'] ?? '');
$location = sanitize($_POST['location'] ?? '');
$description = sanitize($_POST['description'] ?? '');

if ($shipment_id > 0 && !empty($status)) {
    // Update shipment status
    $stmt = $pdo->prepare("UPDATE shipments SET status = ? WHERE id = ?");
    $stmt->execute([$status, $shipment_id]);
    
    // Add tracking history
    $tracking_desc = $description ?: 'Status updated to ' . str_replace('_', ' ', $status);
    if ($location) {
        $tracking_desc .= ' at ' . $location;
    }
    
    $stmt = $pdo->prepare("INSERT INTO shipment_tracking 
        (shipment_id, status, location, description, created_by) 
        VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$shipment_id, $status, $location, $tracking_desc, $_SESSION['admin_id']]);
    
    $_SESSION['success_msg'] = 'Tracking update added successfully!';
}

header('Location: view-shipment.php?id=' . $shipment_id);
exit;
?>