<?php
// delivery_login.php
session_start();
require_once __DIR__ . '/../include/db.php'; // adjust path if needed

// If already logged in (valid session) -> go to dashboard
if (isset($_SESSION['delivery_man_id'])) {
    header("Location: dashboard.php");
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = trim($_POST['phone'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if ($phone === '' || $password === '') {
        $error = "Please enter phone and password.";
    } else {
        // Prepared statement to avoid injection
        $stmt = $conn->prepare("SELECT id, name, phone, password, active FROM delivery_men WHERE phone = ? LIMIT 1");
        $stmt->bind_param("s", $phone);
        $stmt->execute();
        $res = $stmt->get_result();

        if ($res && $res->num_rows === 1) {
            $user = $res->fetch_assoc();
            if ((int)$user['active'] !== 1) {
                $error = "Account is inactive. Contact admin.";
            } elseif (password_verify($password, $user['password'])) {
                // success: set session using the same key dashboard checks
                $_SESSION['delivery_man_id'] = $user['id'];
                $_SESSION['delivery_man_name'] = $user['name'];
                // redirect to dashboard
                header("Location: dashboard.php");
                exit;
            } else {
                $error = "Wrong phone or password.";
            }
        } else {
            $error = "Wrong phone or password.";
        }
        $stmt->close();
    }
}
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Delivery Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background:#f3f6fb; font-family: Arial, sans-serif; }
        .box { max-width:420px; margin:70px auto; }
    </style>
</head>

<body>
<div class="box">
    <div class="card shadow">
        <div class="card-body">
            <h4 class="text-center mb-3">Delivery Login</h4>

            <?php if ($error): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <form method="post" autocomplete="off">
                <div class="mb-3">
                    <label class="form-label">Phone</label>
                    <input type="text" name="phone" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Password</label>
                    <input type="password" name="password" class="form-control" required>
                </div>

                <button class="btn btn-primary w-100">Login</button>
            </form>

        </div>
    </div>
</div>
</body>
</html>
