<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../middleware/auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonError('Method not allowed', 405);

$body     = getBody();
$email    = strtolower(trim($body['email'] ?? ''));
$password = $body['password'] ?? '';

if (!$email || !$password) jsonError('Email and password are required');

$db   = getDB();
$stmt = $db->prepare('SELECT id, name, email, phone, role, password FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password'])) {
    jsonError('Invalid email or password', 401);
}

$token = jwtCreate([
    'id'    => $user['id'],
    'email' => $user['email'],
    'role'  => $user['role'],
    'name'  => $user['name'],
]);

unset($user['password']);
jsonResponse(['token' => $token, 'user' => $user]);
