<?php
session_start();

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

$errorMessage = "";

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

function verify_admin_password($inputPassword, $storedPassword) {
    if (password_verify($inputPassword, $storedPassword)) {
        return "hashed";
    }

    $passwordInfo = password_get_info($storedPassword);
    $isHashed = !empty($passwordInfo['algo']);

    if (!$isHashed && hash_equals($storedPassword, $inputPassword)) {
        return "legacy";
    }

    return false;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $adminUsername = trim($_POST['username'] ?? '');
    $adminPassword = trim($_POST['password'] ?? '');

    if ($adminUsername === '' || $adminPassword === '') {
        $errorMessage = "Please enter your username and password.";
    } else {
       $servername = "localhost";
$username = "dannygym_k-xprex";
$password = "Sasketchwan,1";
$dbname = "dannygym_ k-xprex";

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

        if ($conn->connect_error) {
            $errorMessage = "Database connection failed.";
        } else {
            $stmt = $conn->prepare("SELECT id, username, password FROM admin WHERE username = ? LIMIT 1");
            $stmt->bind_param("s", $adminUsername);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result && $result->num_rows === 1) {
                $admin = $result->fetch_assoc();
                $verificationStatus = verify_admin_password($adminPassword, $admin['password']);

                if ($verificationStatus !== false) {
                    if ($verificationStatus === "legacy") {
                        $newHash = password_hash($adminPassword, PASSWORD_DEFAULT);

                        $upgradeStmt = $conn->prepare("UPDATE admin SET password = ? WHERE id = ?");
                        $upgradeStmt->bind_param("si", $newHash, $admin['id']);
                        $upgradeStmt->execute();
                        $upgradeStmt->close();
                    }

                    session_regenerate_id(true);

                    $_SESSION['admin_logged_in'] = true;
                    $_SESSION['admin_username'] = $admin['username'];

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

                    header("Location: dashboard.php");
                    exit();
                } else {
                    $errorMessage = "Invalid username or password.";
                }
            } else {
                $errorMessage = "Invalid username or password.";
            }

            $stmt->close();
            $conn->close();
        }
    }
}
?>

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

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

        body {
            margin: 0;
            min-height: 100vh;
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #071a3d 0%, #0d2f66 55%, #01ba7c 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
            color: #172033;
        }

        .login-wrapper {
            width: 100%;
            max-width: 430px;
        }

        .login-card {
            background: #fff;
            border-radius: 22px;
            padding: 36px;
            box-shadow: 0 30px 80px rgba(0, 0, 0, 0.24);
        }

        .brand {
            text-align: center;
            margin-bottom: 26px;
        }

        .brand-logo {
            font-size: 31px;
            font-weight: 900;
            color: #071a3d;
        }

        .brand-logo span {
            color: #01ba7c;
        }

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

        h2 {
            margin: 0 0 24px;
            text-align: center;
            color: #071a3d;
            font-size: 22px;
        }

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

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

        input {
            width: 100%;
            padding: 14px 15px;
            border: 1px solid #dce3ee;
            border-radius: 12px;
            font-size: 15px;
            outline: none;
        }

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

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

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

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

        .note {
            margin-top: 20px;
            text-align: center;
            font-size: 13px;
            color: #647084;
            line-height: 1.5;
        }

        @media (max-width: 480px) {
            .login-card {
                padding: 28px 22px;
            }

            .brand-logo {
                font-size: 27px;
            }
        }
    </style>
</head>

<body>

<div class="login-wrapper">
    <div class="login-card">
        <div class="brand">
            <div class="brand-logo">K-<span>Express</span></div>
            <p>Shipment Management Admin Panel</p>
        </div>

        <h2>Admin Login</h2>

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

        <form method="POST" action="">
            <div class="form-group">
                <label for="username">Username</label>
                <input 
                    type="text" 
                    id="username" 
                    name="username" 
                    placeholder="Enter admin username"
                    required
                    autocomplete="username"
                >
            </div>

            <div class="form-group">
                <label for="password">Password</label>
                <input 
                    type="password" 
                    id="password" 
                    name="password" 
                    placeholder="Enter admin password"
                    required
                    autocomplete="current-password"
                >
            </div>

            <button type="submit" class="btn">Login to Dashboard</button>
        </form>

        <div class="note">
            Secure access only. Unauthorized users are not allowed.
        </div>
    </div>
</div>

</body>
</html>