<?php

// Public JSON API for the rider delivery app. Uses distinct session keys (rider_id, rider_name)
// so it never collides with the admin panel's Auth session or the customer app's session.
class RiderAuthController extends Controller
{
    private function jsonInput(): array
    {
        $raw = file_get_contents('php://input');
        $data = json_decode($raw, true);
        return is_array($data) ? $data : [];
    }

    public function login(): void
    {
        $body = $this->jsonInput();
        $username = trim($body['username'] ?? '');
        $password = (string) ($body['password'] ?? '');

        if ($username === '' || $password === '') {
            $this->json(['success' => false, 'message' => 'Please enter your username and password.'], 422);
            return;
        }

        $db = Database::getConnection();
        $stmt = $db->prepare(
            "SELECT u.*, r.role_name FROM users u
             JOIN roles r ON r.id = u.role_id
             WHERE u.username = :username AND u.is_active = 1 AND r.role_name = 'RIDER' LIMIT 1"
        );
        $stmt->execute(['username' => $username]);
        $rider = $stmt->fetch();

        if (!$rider || !password_verify($password, $rider['password_hash'])) {
            $this->json(['success' => false, 'message' => 'Incorrect username or password.'], 401);
            return;
        }

        session_regenerate_id(true);
        $_SESSION['rider_id']   = (int) $rider['id'];
        $_SESSION['rider_name'] = $rider['full_name'];

        $this->json(['success' => true, 'rider' => $this->publicRider($rider)]);
    }

    public function logout(): void
    {
        unset($_SESSION['rider_id'], $_SESSION['rider_name']);
        $this->json(['success' => true]);
    }

    public function me(): void
    {
        if (empty($_SESSION['rider_id'])) {
            $this->json(['success' => true, 'loggedIn' => false]);
            return;
        }

        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT * FROM users WHERE id = :id AND is_active = 1 LIMIT 1");
        $stmt->execute(['id' => $_SESSION['rider_id']]);
        $rider = $stmt->fetch();

        if (!$rider) {
            unset($_SESSION['rider_id'], $_SESSION['rider_name']);
            $this->json(['success' => true, 'loggedIn' => false]);
            return;
        }

        $this->json(['success' => true, 'loggedIn' => true, 'rider' => $this->publicRider($rider)]);
    }

    private function publicRider(array $rider): array
    {
        return [
            'id'             => (int) $rider['id'],
            'name'           => $rider['full_name'],
            'phone'          => $rider['phone'] ?? null,
            'vehicle_type'   => $rider['vehicle_type'] ?? null,
            'vehicle_number' => $rider['vehicle_number'] ?? null,
            'photo_url'      => !empty($rider['photo_path']) ? BASE_URL . '/' . $rider['photo_path'] : null,
        ];
    }
}
