<?php
require_once '../../includes/functions.php';
setCORSHeaders();

// Verify API Hash
verifyAPIHash();

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

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    sendError('Invalid JSON data');
}

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

// Validation
if (empty($email) || empty($password)) {
    sendError('Email and password are required');
}

if (!validateEmail($email)) {
    sendError('Invalid email format');
}

// Get user by email
$user = getUserByEmail($email);
if (!$user) {
    sendError('Invalid email or password');
}

// Check if user is active
if (!$user['is_active']) {
    sendError('Account is disabled. Please contact administrator.');
}

// Verify password
if (!password_verify($password, $user['password'])) {
    sendError('Invalid email or password');
}

// Generate JWT token
$token = generateJWT([
    'user_id' => $user['id'],
    'username' => $user['username'],
    'email' => $user['email'],
    'exp' => time() + (60 * 60 * 24 * 7) // 7 days
]);

// Remove password from user data
unset($user['password']);

sendResponse([
    'success' => true,
    'message' => 'Login successful',
    'data' => [
        'token' => $token,
        'user' => $user
    ]
]);
?>
