<?php
/**
 * API Login Endpoint - JSON response for mobile app
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

// Only POST allowed
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

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

// Validate input
if (empty($email) || empty($password)) {
    echo json_encode(['success' => false, 'error' => 'Email and password are required']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'error' => 'Invalid email format']);
    exit;
}

try {
    $user = dbFetch("SELECT * FROM users WHERE email = ?", [$email]);

    if (!$user || !password_verify($password, $user['password'])) {
        echo json_encode(['success' => false, 'error' => 'Invalid email or password']);
        exit;
    }

    if ($user['status'] !== 'active') {
        echo json_encode(['success' => false, 'error' => 'Your account is not active. Please contact support.']);
        exit;
    }

    // Set session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_type'] = 'user';
    $_SESSION['user_email'] = $user['email'];
    $_SESSION['account_type'] = 'demo';

    // Update last login
    dbQuery("UPDATE users SET last_login = NOW() WHERE id = ?", [$user['id']]);

    // Build user name
    $name = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
    if (empty($name)) {
        $name = $user['name'] ?? $user['email'];
    }

    echo json_encode([
        'success' => true,
        'message' => 'Login successful',
        'data' => [
            'id'            => (int)$user['id'],
            'user_id'       => $user['user_id'] ?? null,
            'name'          => $name,
            'email'         => $user['email'],
            'phone'         => $user['phone'] ?? null,
            'status'        => $user['status'],
            'kyc_status'    => $user['kyc_status'] ?? 'pending',
            'referral_code' => $user['referral_code'] ?? null
        ]
    ]);

} catch (Exception $e) {
    error_log("API Login Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Server error. Please try again.']);
}
