<?php
// update_location.php

session_start();

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: index.php");
    exit();
}

$servername = "localhost";
$username = "dannygym_k-xprex";
$password = "Sasketchwan,1";
$dbname = "dannygym_ k-xprex";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Database connection failed.");
}

function clean_output($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

$successMessage = "";
$errorMessage = "";

$trackingNumber = trim($_GET['tracking_number'] ?? $_POST['tracking_number'] ?? '');
$client = null;

/* Fetch client if tracking number is available */
if ($trackingNumber !== '') {
    $clientStmt = $conn->prepare("
        SELECT tracking_number, sender_name, sender_location, receiver_name, receiver_location
        FROM clients
        WHERE tracking_number = ?
        LIMIT 1
    ");

    $clientStmt->bind_param("s", $trackingNumber);
    $clientStmt->execute();
    $clientResult = $clientStmt->get_result();

    if ($clientResult && $clientResult->num_rows === 1) {
        $client = $clientResult->fetch_assoc();
    }

    $clientStmt->close();
}

/* Save new location update */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $location = trim($_POST['location'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $latitude = trim($_POST['latitude'] ?? '');
    $longitude = trim($_POST['longitude'] ?? '');
    $date = trim($_POST['date'] ?? '');
    $time = trim($_POST['time'] ?? '');

    if ($trackingNumber === '') {
        $errorMessage = "Please enter a tracking number.";
    } elseif ($client === null) {
        $errorMessage = "No client found with this tracking number.";
    } elseif ($location === '') {
        $errorMessage = "Please enter the current location.";
    } elseif ($description === '') {
        $errorMessage = "Please enter a location description.";
    } elseif ($date === '') {
        $errorMessage = "Please select a date.";
    } elseif ($time === '') {
        $errorMessage = "Please select a time.";
    } elseif ($latitude !== '' && !is_numeric($latitude)) {
        $errorMessage = "Latitude must be a valid number.";
    } elseif ($longitude !== '' && !is_numeric($longitude)) {
        $errorMessage = "Longitude must be a valid number.";
    } else {
        $latitudeValue = $latitude !== '' ? (float)$latitude : null;
        $longitudeValue = $longitude !== '' ? (float)$longitude : null;

        $insertStmt = $conn->prepare("
            INSERT INTO location_history (
                tracking_number,
                location,
                description,
                latitude,
                longitude,
                `date`,
                `time`
            ) VALUES (?, ?, ?, ?, ?, ?, ?)
        ");

        if (!$insertStmt) {
            $errorMessage = "Unable to prepare location update.";
        } else {
            $insertStmt->bind_param(
                "sssddss",
                $trackingNumber,
                $location,
                $description,
                $latitudeValue,
                $longitudeValue,
                $date,
                $time
            );

            if ($insertStmt->execute()) {
                $successMessage = "Location update added successfully.";
            } else {
                $errorMessage = "Unable to save location update. Please try again.";
            }

            $insertStmt->close();
        }
    }
}

/* Fetch location history */
$historyResult = null;

if ($trackingNumber !== '') {
    $historyStmt = $conn->prepare("
        SELECT location, description, latitude, longitude, `date`, `time`
        FROM location_history
        WHERE tracking_number = ?
        ORDER BY `date` DESC, `time` DESC, id DESC
    ");

    $historyStmt->bind_param("s", $trackingNumber);
    $historyStmt->execute();
    $historyResult = $historyStmt->get_result();
}

/* Fetch clients for dropdown */
$clientsResult = $conn->query("
    SELECT tracking_number, sender_name, receiver_name
    FROM clients
    ORDER BY id DESC
");

$today = date("Y-m-d");
$currentTime = date("H:i");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Update Location - K-Express Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f4f7fb;
            color: #172033;
        }

        .admin-layout {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 260px;
            background: #071a3d;
            color: #fff;
            padding: 28px 20px;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
        }

        .brand {
            font-size: 23px;
            font-weight: 800;
            margin-bottom: 35px;
        }

        .brand span {
            color: #01ba7c;
        }

        .nav-link {
            display: block;
            color: #d7deea;
            text-decoration: none;
            padding: 13px 14px;
            border-radius: 10px;
            margin-bottom: 8px;
            font-size: 15px;
        }

        .nav-link:hover,
        .nav-link.active {
            background: #01ba7c;
            color: #fff;
        }

        .main-content {
            margin-left: 260px;
            width: calc(100% - 260px);
            padding: 32px;
        }

        .topbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #fff;
            padding: 22px 24px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(7, 26, 61, 0.06);
            margin-bottom: 28px;
        }

        .topbar h1 {
            margin: 0;
            font-size: 25px;
            color: #071a3d;
        }

        .topbar p {
            margin: 6px 0 0;
            color: #647084;
            font-size: 14px;
        }

        .btn {
            display: inline-block;
            padding: 12px 18px;
            border-radius: 10px;
            text-decoration: none;
            font-weight: 700;
            font-size: 14px;
        }

        .btn-dark {
            background: #071a3d;
            color: #fff;
        }

        .btn-green {
            background: #01ba7c;
            color: #fff;
        }

        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }

        .card {
            background: #fff;
            border-radius: 18px;
            padding: 28px;
            box-shadow: 0 10px 30px rgba(7, 26, 61, 0.06);
        }

        .card h2 {
            margin: 0 0 18px;
            color: #071a3d;
            font-size: 20px;
            padding-bottom: 12px;
            border-bottom: 1px solid #edf0f5;
        }

        .client-summary {
            background: #f8fafc;
            border: 1px solid #edf0f5;
            border-radius: 14px;
            padding: 16px;
            margin-bottom: 22px;
        }

        .client-summary p {
            margin: 8px 0;
            color: #344054;
        }

        .tracking-code {
            display: inline-block;
            background: #e8fff6;
            color: #027a52;
            font-weight: 800;
            padding: 7px 10px;
            border-radius: 8px;
        }

        .form-group {
            margin-bottom: 18px;
        }

        label {
            display: block;
            font-weight: 700;
            font-size: 14px;
            margin-bottom: 8px;
            color: #27344d;
        }

        input,
        select,
        textarea {
            width: 100%;
            padding: 13px 14px;
            border: 1px solid #dce3ee;
            border-radius: 10px;
            font-size: 15px;
            outline: none;
            background: #fff;
            color: #172033;
        }

        textarea {
            min-height: 110px;
            resize: vertical;
        }

        input:focus,
        select:focus,
        textarea:focus {
            border-color: #01ba7c;
            box-shadow: 0 0 0 4px rgba(1, 186, 124, 0.12);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .submit-btn {
            width: 100%;
            border: none;
            background: #01ba7c;
            color: #fff;
            padding: 15px 20px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 800;
            cursor: pointer;
        }

        .submit-btn:hover {
            background: #019f69;
        }

        .alert {
            padding: 15px 16px;
            border-radius: 12px;
            font-weight: 700;
            margin-bottom: 20px;
        }

        .alert-success {
            background: #e8fff6;
            color: #036b48;
            border: 1px solid #b7f2dc;
        }

        .alert-error {
            background: #fff1f1;
            color: #a72828;
            border: 1px solid #ffc8c8;
        }

        .table-wrap {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 760px;
        }

        th {
            background: #f4f7fb;
            color: #071a3d;
            text-align: left;
            padding: 13px;
            font-size: 13px;
            text-transform: uppercase;
            border-bottom: 1px solid #e6ebf2;
        }

        td {
            padding: 13px;
            border-bottom: 1px solid #edf0f5;
            color: #344054;
            font-size: 14px;
            vertical-align: top;
        }

        .empty-state {
            text-align: center;
            padding: 30px 15px;
            color: #647084;
            font-weight: 700;
        }

        .note {
            font-size: 13px;
            color: #647084;
            line-height: 1.6;
            margin-top: 10px;
        }

        @media (max-width: 1050px) {
            .grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 900px) {
            .sidebar {
                position: static;
                width: 100%;
                height: auto;
            }

            .admin-layout {
                display: block;
            }

            .main-content {
                margin-left: 0;
                width: 100%;
                padding: 20px;
            }

            .topbar {
                flex-direction: column;
                align-items: flex-start;
                gap: 16px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>

<div class="admin-layout">
    <aside class="sidebar">
        <div class="brand">K-<span>Express</span></div>

        <a href="dashboard.php" class="nav-link">Dashboard</a>
        <a href="create_client.php" class="nav-link">Create Client</a>
        <a href="update_location.php" class="nav-link active">Update Location</a>
        <a href="view_clients.php" class="nav-link">View Clients</a>
        <a href="change_admin_password.php" class="nav-link">Change Password</a>
        <a href="logout.php" class="nav-link">Logout</a>
    </aside>

    <main class="main-content">
        <div class="topbar">
            <div>
                <h1>Update Location</h1>
                <p>Add shipment movement updates for customer tracking.</p>
            </div>

            <a href="dashboard.php" class="btn btn-dark">Back to Dashboard</a>
        </div>

        <div class="grid">
            <div class="card">
                <h2>Add Location Update</h2>

                <?php if ($successMessage !== '') { ?>
                    <div class="alert alert-success">
                        <?php echo clean_output($successMessage); ?>
                    </div>
                <?php } ?>

                <?php if ($errorMessage !== '') { ?>
                    <div class="alert alert-error">
                        <?php echo clean_output($errorMessage); ?>
                    </div>
                <?php } ?>

                <?php if ($client !== null) { ?>
                    <div class="client-summary">
                        <p>
                            <strong>Tracking Number:</strong>
                            <span class="tracking-code"><?php echo clean_output($client['tracking_number']); ?></span>
                        </p>
                        <p><strong>Sender:</strong> <?php echo clean_output($client['sender_name']); ?></p>
                        <p><strong>From:</strong> <?php echo clean_output($client['sender_location']); ?></p>
                        <p><strong>Receiver:</strong> <?php echo clean_output($client['receiver_name']); ?></p>
                        <p><strong>To:</strong> <?php echo clean_output($client['receiver_location']); ?></p>
                    </div>
                <?php } ?>

                <form method="POST" action="">
                    <div class="form-group">
                        <label for="tracking_number">Tracking Number</label>
                        <select id="tracking_number" name="tracking_number" required onchange="window.location='update_location.php?tracking_number=' + encodeURIComponent(this.value)">
                            <option value="">Select Tracking Number</option>

                            <?php if ($clientsResult && $clientsResult->num_rows > 0) { ?>
                                <?php while ($clientOption = $clientsResult->fetch_assoc()) { ?>
                                    <option 
                                        value="<?php echo clean_output($clientOption['tracking_number']); ?>"
                                        <?php echo $trackingNumber === $clientOption['tracking_number'] ? 'selected' : ''; ?>
                                    >
                                        <?php echo clean_output($clientOption['tracking_number']); ?> — 
                                        <?php echo clean_output($clientOption['sender_name']); ?> to 
                                        <?php echo clean_output($clientOption['receiver_name']); ?>
                                    </option>
                                <?php } ?>
                            <?php } ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="location">Current Location</label>
                        <input 
                            type="text" 
                            id="location" 
                            name="location" 
                            placeholder="Example: Lagos Sorting Center"
                            required
                        >
                    </div>

                    <div class="form-group">
                        <label for="description">Location Description</label>
                        <textarea 
                            id="description" 
                            name="description" 
                            placeholder="Example: Package received and currently being processed"
                            required
                        ></textarea>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="latitude">Latitude</label>
                            <input 
                                type="number" 
                                step="0.00000001" 
                                id="latitude" 
                                name="latitude" 
                                placeholder="Example: 6.524379"
                            >
                        </div>

                        <div class="form-group">
                            <label for="longitude">Longitude</label>
                            <input 
                                type="number" 
                                step="0.00000001" 
                                id="longitude" 
                                name="longitude" 
                                placeholder="Example: 3.379206"
                            >
                        </div>
                    </div>

                    <div class="note">
                        Latitude and longitude are needed if you want the map route line to show correctly.
                    </div>

                    <div class="form-row" style="margin-top:18px;">
                        <div class="form-group">
                            <label for="date">Date</label>
                            <input 
                                type="date" 
                                id="date" 
                                name="date" 
                                value="<?php echo clean_output($today); ?>"
                                required
                            >
                        </div>

                        <div class="form-group">
                            <label for="time">Time</label>
                            <input 
                                type="time" 
                                id="time" 
                                name="time" 
                                value="<?php echo clean_output($currentTime); ?>"
                                required
                            >
                        </div>
                    </div>

                    <button type="submit" class="submit-btn">Save Location Update</button>
                </form>
            </div>

            <div class="card">
                <h2>Location History</h2>

                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Location</th>
                                <th>Description</th>
                                <th>Latitude</th>
                                <th>Longitude</th>
                                <th>Date</th>
                                <th>Time</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if ($trackingNumber === '') { ?>
                                <tr>
                                    <td colspan="6" class="empty-state">
                                        Select a tracking number to view location history.
                                    </td>
                                </tr>
                            <?php } elseif ($historyResult && $historyResult->num_rows > 0) { ?>
                                <?php while ($history = $historyResult->fetch_assoc()) { ?>
                                    <tr>
                                        <td><?php echo clean_output($history['location']); ?></td>
                                        <td><?php echo clean_output($history['description']); ?></td>
                                        <td><?php echo clean_output($history['latitude']); ?></td>
                                        <td><?php echo clean_output($history['longitude']); ?></td>
                                        <td><?php echo clean_output($history['date']); ?></td>
                                        <td><?php echo clean_output($history['time']); ?></td>
                                    </tr>
                                <?php } ?>
                            <?php } else { ?>
                                <tr>
                                    <td colspan="6" class="empty-state">
                                        No location history found for this tracking number.
                                    </td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($trackingNumber !== '') { ?>
                    <p class="note">
                        <a class="btn btn-green" href="display_history.php?tracking_number=<?php echo urlencode($trackingNumber); ?>" target="_blank">
                            View Customer Tracking Page
                        </a>
                    </p>
                <?php } ?>
            </div>
        </div>
    </main>
</div>

</body>
</html>

<?php
if (isset($historyStmt)) {
    $historyStmt->close();
}

$conn->close();
?>