<?php
// api/login.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }

require_once __DIR__ . '/../inc/db.php';
require_once __DIR__ . '/../inc/functions.php';

$data = get_post_data();
$email = trim($data['email'] ?? '');
$password = $data['password'] ?? '';

if (!$email || !$password) {
    send_json(['status'=>false,'msg'=>'Email and password required']);
}

$stmt = $conn->prepare("SELECT id, name, password FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$res = $stmt->get_result();
$user = $res->fetch_assoc();
$stmt->close();

if ($user && password_verify($password, $user['password'])) {
    // generate new token and save
    $token = create_api_token(32);
    $upd = $conn->prepare("UPDATE users SET api_token = ? WHERE id = ?");
    $upd->bind_param("si", $token, $user['id']);
    $upd->execute();
    $upd->close();

    send_json(['status'=>true,'msg'=>'Login successful','data'=>[
        'id' => $user['id'],
        'name' => $user['name'],
        'email' => $email,
        'api_token' => $token
    ]]);
} else {
    send_json(['status'=>false,'msg'=>'Invalid email or password']);
}
?>
