<?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');
}

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

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

$errorMessage = "";
$client = null;

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

if ($result && $result->num_rows === 1) {
    $client = $result->fetch_assoc();
} else {
    $stmt->close();
    $conn->close();
    header("Location: dashboard.php");
    exit();
}

$stmt->close();

/* Delete only after confirmation */
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $conn->begin_transaction();

    try {
        $historyStmt = $conn->prepare("DELETE FROM location_history WHERE tracking_number = ?");
        $historyStmt->bind_param("s", $trackingNumber);
        $historyStmt->execute();
        $historyStmt->close();

        $clientStmt = $conn->prepare("DELETE FROM clients WHERE tracking_number = ?");
        $clientStmt->bind_param("s", $trackingNumber);
        $clientStmt->execute();

        if ($clientStmt->affected_rows < 1) {
            throw new Exception("Client could not be deleted.");
        }

        $clientStmt->close();

        $conn->commit();
        $conn->close();

        header("Location: dashboard.php?deleted=1");
        exit();

    } catch (Exception $e) {
        $conn->rollback();
        $errorMessage = "Unable to delete client. Please try again.";
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Delete 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 {
            background: #01ba7c;
            color: #fff;
        }

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

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

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

        .warning-icon {
            width: 58px;
            height: 58px;
            border-radius: 50%;
            background: #fff1f1;
            color: #b42318;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28px;
            font-weight: 900;
            margin-bottom: 18px;
        }

        .delete-card h2 {
            margin: 0 0 12px;
            color: #071a3d;
            font-size: 24px;
        }

        .delete-card p {
            color: #647084;
            line-height: 1.6;
        }

        .client-box {
            background: #f8fafc;
            border: 1px solid #edf0f5;
            border-radius: 14px;
            padding: 18px;
            margin: 22px 0;
        }

        .client-box div {
            margin-bottom: 10px;
        }

        .client-box div:last-child {
            margin-bottom: 0;
        }

        .client-box strong {
            color: #071a3d;
        }

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

        .actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-top: 24px;
        }

        .delete-btn {
            border: none;
            background: #b42318;
            color: #fff;
            padding: 14px 20px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 800;
            cursor: pointer;
        }

        .delete-btn:hover {
            background: #912018;
        }

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

        .alert-error {
            background: #fff1f1;
            color: #a72828;
            border: 1px solid #ffc8c8;
            padding: 14px 16px;
            border-radius: 12px;
            font-weight: 700;
            margin-bottom: 18px;
        }

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

            .admin-layout {
                display: block;
            }

            .main-content {
                margin-left: 0;
                width: 100%;
                padding: 20px;
            }
        }
    </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">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">
            <h1>Delete Client</h1>
            <p>Confirm before permanently removing this shipment record.</p>
        </div>

        <div class="delete-card">
            <div class="warning-icon">!</div>

            <h2>Are you sure you want to delete this client?</h2>
            <p>
                This action will remove the client record and all related location history for this tracking number.
                This cannot be undone.
            </p>

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

            <div class="client-box">
                <div>
                    <strong>Tracking Number:</strong>
                    <span class="tracking-code"><?php echo clean_output($client['tracking_number']); ?></span>
                </div>

                <div>
                    <strong>Sender:</strong>
                    <?php echo clean_output($client['sender_name']); ?>
                </div>

                <div>
                    <strong>Receiver:</strong>
                    <?php echo clean_output($client['receiver_name']); ?>
                </div>

                <div>
                    <strong>Receiver Location:</strong>
                    <?php echo clean_output($client['receiver_location']); ?>
                </div>
            </div>

            <form method="POST" action="">
                <input type="hidden" name="tracking_number" value="<?php echo clean_output($trackingNumber); ?>">

                <div class="actions">
                    <button type="submit" class="delete-btn">Yes, Delete Client</button>
                    <a href="dashboard.php" class="cancel-btn">Cancel</a>
                </div>
            </form>
        </div>
    </main>
</div>

</body>
</html>