<?php
// edit_client.php

// session_start();
// if (!isset($_SESSION['username'])) {
//     header('Location: login.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');
}

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

if ($trackingNumber === '') {
    header('Location: dashboard.php');
    exit();
}

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

/* Fetch existing client */
$stmt = $conn->prepare("SELECT * FROM clients WHERE tracking_number = ? LIMIT 1");
$stmt->bind_param("s", $trackingNumber);
$stmt->execute();
$result = $stmt->get_result();

if (!$result || $result->num_rows !== 1) {
    $stmt->close();
    $conn->close();
    header('Location: dashboard.php');
    exit();
}

$row = $result->fetch_assoc();
$stmt->close();

$senderName = $row['sender_name'];
$senderLocation = $row['sender_location'];
$locationDescription = $row['location_description'];
$senderTimeRaw = $row['sender_time'];
$receiverName = $row['receiver_name'];
$receiverLocation = $row['receiver_location'];
$receiverPhone = $row['receiver_phone'];
$receiverEmail = $row['receiver_email'];
$packageWeight = $row['package_weight'];
$deliveryAmount = $row['delivery_amount'];
$dateSent = $row['date_sent'];
$arrivalDate = $row['arrival_date'];

$senderTimeForInput = "";

if (!empty($senderTimeRaw)) {
    $senderTimeForInput = date("H:i", strtotime($senderTimeRaw));
}

/* Update client */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $senderName = trim($_POST['sender_name'] ?? '');
    $senderLocation = trim($_POST['sender_location'] ?? '');
    $locationDescription = trim($_POST['location_description'] ?? '');
    $senderTime = trim($_POST['sender_time'] ?? '');
    $receiverName = trim($_POST['receiver_name'] ?? '');
    $receiverLocation = trim($_POST['receiver_location'] ?? '');
    $receiverPhone = trim($_POST['receiver_phone'] ?? '');
    $receiverEmail = trim($_POST['receiver_email'] ?? '');
    $packageWeight = trim($_POST['package_weight'] ?? '');
    $deliveryAmount = trim($_POST['delivery_amount'] ?? '');
    $dateSent = trim($_POST['date_sent'] ?? '');
    $arrivalDate = trim($_POST['arrival_date'] ?? '');

    if (
        $senderName === '' ||
        $senderLocation === '' ||
        $receiverName === '' ||
        $receiverLocation === '' ||
        $receiverPhone === '' ||
        $receiverEmail === '' ||
        $packageWeight === '' ||
        $deliveryAmount === '' ||
        $dateSent === '' ||
        $arrivalDate === ''
    ) {
        $errorMessage = "Please fill all required fields.";
    } elseif (!filter_var($receiverEmail, FILTER_VALIDATE_EMAIL)) {
        $errorMessage = "Please enter a valid receiver email address.";
    } elseif (!is_numeric($packageWeight) || $packageWeight <= 0) {
        $errorMessage = "Package weight must be a valid number.";
    } elseif (!is_numeric($deliveryAmount) || $deliveryAmount < 0) {
        $errorMessage = "Delivery amount must be a valid number.";
    } else {
        if ($senderTime !== '') {
            $senderDateTime = $dateSent . " " . $senderTime . ":00";
        } else {
            $senderDateTime = $dateSent . " 00:00:00";
        }

        $packageWeight = (float)$packageWeight;
        $deliveryAmount = (float)$deliveryAmount;

        $updateStmt = $conn->prepare("
            UPDATE clients SET
                sender_name = ?,
                sender_location = ?,
                location_description = ?,
                sender_time = ?,
                receiver_name = ?,
                receiver_location = ?,
                receiver_phone = ?,
                receiver_email = ?,
                package_weight = ?,
                delivery_amount = ?,
                date_sent = ?,
                arrival_date = ?
            WHERE tracking_number = ?
        ");

        if (!$updateStmt) {
            $errorMessage = "Unable to prepare update request.";
        } else {
            $updateStmt->bind_param(
                "ssssssssddsss",
                $senderName,
                $senderLocation,
                $locationDescription,
                $senderDateTime,
                $receiverName,
                $receiverLocation,
                $receiverPhone,
                $receiverEmail,
                $packageWeight,
                $deliveryAmount,
                $dateSent,
                $arrivalDate,
                $trackingNumber
            );

            if ($updateStmt->execute()) {
                $successMessage = "Client details updated successfully.";
                $senderTimeForInput = $senderTime;
            } else {
                $errorMessage = "Unable to update client details. Please try again.";
            }

            $updateStmt->close();
        }
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Client - 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-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .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;
        }

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

        .tracking-box {
            background: #e8fff6;
            color: #036b48;
            padding: 14px 16px;
            border-radius: 12px;
            font-weight: 800;
            margin-bottom: 24px;
            display: inline-block;
        }

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

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 28px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full {
            grid-column: 1 / -1;
        }

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

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

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

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

        .actions {
            display: flex;
            align-items: center;
            gap: 14px;
            margin-top: 10px;
            flex-wrap: wrap;
        }

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

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

        .cancel-btn {
            background: #eef2f7;
            color: #071a3d;
            padding: 14px 22px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 800;
            text-decoration: none;
        }

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

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

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

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

            .admin-layout {
                display: block;
            }

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

            .form-grid {
                grid-template-columns: 1fr;
            }

            .topbar {
                flex-direction: column;
                align-items: flex-start;
                gap: 16px;
            }
        }
    </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?tracking_number=<?php echo urlencode($trackingNumber); ?>" class="nav-link">Update Location</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>Edit Client</h1>
                <p>Update shipment and customer details without corrupting location history.</p>
            </div>

            <div class="btn-group">
                <a href="display_history.php?tracking_number=<?php echo urlencode($trackingNumber); ?>" target="_blank" class="btn btn-green">
                    View Tracking
                </a>
                <a href="dashboard.php" class="btn btn-dark">
                    Back to Dashboard
                </a>
            </div>
        </div>

        <?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 } ?>

        <form class="form-card" method="POST" action="">
            <div class="tracking-box">
                Tracking Number: <?php echo clean_output($trackingNumber); ?>
            </div>

            <h2 class="section-title">Sender Information</h2>

            <div class="form-grid">
                <div class="form-group">
                    <label for="sender_name">Sender Name</label>
                    <input type="text" id="sender_name" name="sender_name" value="<?php echo clean_output($senderName); ?>" required>
                </div>

                <div class="form-group">
                    <label for="sender_location">Sender Location</label>
                    <input type="text" id="sender_location" name="sender_location" value="<?php echo clean_output($senderLocation); ?>" required>
                </div>

                <div class="form-group full">
                    <label for="location_description">Location Description</label>
                    <textarea id="location_description" name="location_description"><?php echo clean_output($locationDescription); ?></textarea>
                </div>

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

                <div class="form-group">
                    <label for="date_sent">Date Sent</label>
                    <input type="date" id="date_sent" name="date_sent" value="<?php echo clean_output($dateSent); ?>" required>
                </div>
            </div>

            <h2 class="section-title">Receiver Information</h2>

            <div class="form-grid">
                <div class="form-group">
                    <label for="receiver_name">Receiver Name</label>
                    <input type="text" id="receiver_name" name="receiver_name" value="<?php echo clean_output($receiverName); ?>" required>
                </div>

                <div class="form-group">
                    <label for="receiver_location">Receiver Location</label>
                    <input type="text" id="receiver_location" name="receiver_location" value="<?php echo clean_output($receiverLocation); ?>" required>
                </div>

                <div class="form-group">
                    <label for="receiver_phone">Receiver Phone</label>
                    <input type="text" id="receiver_phone" name="receiver_phone" value="<?php echo clean_output($receiverPhone); ?>" required>
                </div>

                <div class="form-group">
                    <label for="receiver_email">Receiver Email</label>
                    <input type="email" id="receiver_email" name="receiver_email" value="<?php echo clean_output($receiverEmail); ?>" required>
                </div>
            </div>

            <h2 class="section-title">Package Information</h2>

            <div class="form-grid">
                <div class="form-group">
                    <label for="package_weight">Package Weight</label>
                    <input type="number" step="0.01" id="package_weight" name="package_weight" value="<?php echo clean_output($packageWeight); ?>" required>
                </div>

                <div class="form-group">
                    <label for="delivery_amount">Delivery Amount</label>
                    <input type="number" step="0.01" id="delivery_amount" name="delivery_amount" value="<?php echo clean_output($deliveryAmount); ?>" required>
                </div>

                <div class="form-group">
                    <label for="arrival_date">Arrival Date</label>
                    <input type="date" id="arrival_date" name="arrival_date" value="<?php echo clean_output($arrivalDate); ?>" required>
                </div>
            </div>

            <div class="actions">
                <button type="submit" class="submit-btn">Save Changes</button>
                <a href="dashboard.php" class="cancel-btn">Cancel</a>
                <a href="update_location.php?tracking_number=<?php echo urlencode($trackingNumber); ?>" class="cancel-btn">Update Location Instead</a>
            </div>
        </form>
    </main>
</div>

</body>
</html>