<?php
// create_client.php

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

function generateTrackingNumber($senderLocation) {
    $prefix = "KEC";
    $randomNumber = random_int(100000, 999999);
    $locationCode = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $senderLocation), 0, 3));

    if ($locationCode === '') {
        $locationCode = 'LOC';
    }

    return $prefix . $randomNumber . $locationCode;
}

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

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 {
        $trackingNumber = generateTrackingNumber($senderLocation);

        // Your clients table uses sender_time as DATETIME.
        // If admin only selects time, combine it with date_sent.
        if ($senderTime !== '') {
            $senderDateTime = $dateSent . " " . $senderTime . ":00";
        } else {
            $senderDateTime = $dateSent . " 00:00:00";
        }

        $stmt = $conn->prepare("
            INSERT INTO clients (
                tracking_number,
                sender_name,
                sender_location,
                location_description,
                sender_time,
                receiver_name,
                receiver_location,
                receiver_phone,
                receiver_email,
                package_weight,
                delivery_amount,
                date_sent,
                arrival_date
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if (!$stmt) {
            $errorMessage = "Unable to prepare client creation request.";
        } else {
            $packageWeight = (float)$packageWeight;
            $deliveryAmount = (float)$deliveryAmount;

            $stmt->bind_param(
                "sssssssssddss",
                $trackingNumber,
                $senderName,
                $senderLocation,
                $locationDescription,
                $senderDateTime,
                $receiverName,
                $receiverLocation,
                $receiverPhone,
                $receiverEmail,
                $packageWeight,
                $deliveryAmount,
                $dateSent,
                $arrivalDate
            );

            if ($stmt->execute()) {
                $createdTrackingNumber = $trackingNumber;
                $successMessage = "Client created successfully.";
            } else {
                $errorMessage = "Unable to create client. Please try again.";
            }

            $stmt->close();
        }
    }
}

$countries = [
    "Nigeria",
    "Ghana",
    "South Africa",
    "Kenya",
    "United States",
    "United Kingdom",
    "Canada",
    "United Arab Emirates",
    "China",
    "India",
    "Germany",
    "France",
    "Italy",
    "Spain",
    "Netherlands",
    "Turkey",
    "Brazil",
    "Australia",
    "Japan",
    "South Korea",
    "Singapore",
    "Qatar",
    "Saudi Arabia",
    "Egypt",
    "Morocco",
    "Cameroon",
    "Benin",
    "Togo",
    "Uganda",
    "Tanzania",
    "Rwanda",
    "Senegal",
    "Ivory Coast",
    "Malaysia",
    "Indonesia",
    "Thailand",
    "Vietnam",
    "Philippines",
    "Pakistan",
    "Bangladesh",
    "Russia",
    "Ukraine",
    "Poland",
    "Portugal",
    "Belgium",
    "Switzerland",
    "Sweden",
    "Norway",
    "Denmark",
    "Finland",
    "Ireland",
    "Mexico",
    "Argentina",
    "New Zealand",
    "Israel",
    "Kuwait",
    "Oman",
    "Bahrain"
];

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create 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: 22px;
            font-weight: 800;
            margin-bottom: 35px;
            letter-spacing: 0.3px;
        }

        .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: 20px 24px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(7, 26, 61, 0.06);
            margin-bottom: 28px;
        }

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

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

        .btn-secondary {
            display: inline-block;
            padding: 12px 18px;
            border-radius: 10px;
            background: #071a3d;
            color: #fff;
            text-decoration: none;
            font-weight: 700;
            font-size: 14px;
        }

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

        .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,
        select,
        textarea {
            width: 100%;
            padding: 13px 14px;
            border: 1px solid #dce3ee;
            border-radius: 10px;
            font-size: 15px;
            background: #fff;
            color: #172033;
            outline: none;
        }

        input:focus,
        select: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;
        }

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

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

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

        .tracking-box {
            margin-top: 12px;
            padding: 14px;
            background: #fff;
            border-radius: 10px;
            border: 1px dashed #01ba7c;
            display: inline-block;
            font-size: 18px;
            color: #071a3d;
        }

        .small-note {
            font-size: 13px;
            color: #647084;
            margin-top: 8px;
        }

        @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 active">Create Client</a>
        <a href="update_location.php" class="nav-link">Update Location</a>
        <a href="view_clients.php" class="nav-link">View Clients</a>
        <a href="logout.php" class="nav-link">Logout</a>
    </aside>

    <main class="main-content">
        <div class="topbar">
            <div>
                <h1>Create Client</h1>
                <p>Add a new shipment record and generate a tracking number.</p>
            </div>

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

        <?php if ($successMessage !== '') { ?>
            <div class="alert alert-success">
                <?php echo clean_output($successMessage); ?><br>
                <div class="tracking-box">
                    Tracking Number: <?php echo clean_output($createdTrackingNumber); ?>
                </div>
                <div class="small-note">Copy this tracking number and share it with the customer.</div>
            </div>
        <?php } ?>

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

        <form class="form-card" method="POST" action="">
            <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" required>
                </div>

                <div class="form-group">
                    <label for="sender_location">Sender Country</label>
                    <select id="sender_location" name="sender_location" required>
                        <option value="">Select Country</option>
                        <?php foreach ($countries as $country) { ?>
                            <option value="<?php echo clean_output($country); ?>">
                                <?php echo clean_output($country); ?>
                            </option>
                        <?php } ?>
                    </select>
                </div>

                <div class="form-group full">
                    <label for="location_description">Location Description</label>
                    <textarea id="location_description" name="location_description" placeholder="Example: Package received at Lagos sorting center"></textarea>
                </div>

                <div class="form-group">
                    <label for="sender_time">Sender Time</label>
                    <input type="time" id="sender_time" name="sender_time">
                </div>

                <div class="form-group">
                    <label for="date_sent">Date Sent</label>
                    <input type="date" id="date_sent" name="date_sent" 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" required>
                </div>

                <div class="form-group">
                    <label for="receiver_location">Receiver Location</label>
                    <input type="text" id="receiver_location" name="receiver_location" required>
                </div>

                <div class="form-group">
                    <label for="receiver_phone">Receiver Phone</label>
                    <input type="text" id="receiver_phone" name="receiver_phone" required>
                </div>

                <div class="form-group">
                    <label for="receiver_email">Receiver Email</label>
                    <input type="email" id="receiver_email" name="receiver_email" 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" 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" required>
                </div>

                <div class="form-group">
                    <label for="arrival_date">Arrival Date</label>
                    <input type="date" id="arrival_date" name="arrival_date" required>
                </div>
            </div>

            <div class="actions">
                <button type="submit" class="submit-btn">Create Client</button>
                <button type="reset" class="reset-btn">Clear Form</button>
            </div>
        </form>
    </main>
</div>

</body>
</html>