<?php
/**
 * Login Handler
 * Process user login/authentication
 */

header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/session.php';

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

$response = ['success' => false, 'message' => ''];

try {
    // Get POST data
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember = isset($_POST['remember']) ? true : false;

    // Validation
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Valid email address is required');
    }
    
    if (empty($password)) {
        throw new Exception('Password is required');
    }

    // Get user from database
    $sql = "SELECT id, first_name, last_name, email, password, user_type, is_active 
            FROM users WHERE email = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception('Email or password is incorrect');
    }

    $user = $result->fetch_assoc();

    // Check if user is active
    if (!$user['is_active']) {
        throw new Exception('This account has been deactivated');
    }

    // Verify password
    if (!password_verify($password, $user['password'])) {
        throw new Exception('Email or password is incorrect');
    }

    // Update last login
    $update_sql = "UPDATE users SET last_login = NOW() WHERE id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param('i', $user['id']);
    $update_stmt->execute();

    // Create session
    loginUser($user['id'], $user['email'], $user['first_name'], $user['last_name'], $user['user_type']);

    // Set remember me cookie if checked
    if ($remember) {
        $cookie_token = bin2hex(random_bytes(32));
        $_SESSION['remember_token'] = $cookie_token;
        setcookie('remember_token', $cookie_token, time() + (86400 * 30), '/');
    }

    $response['success'] = true;
    $response['message'] = 'Login successful! Redirecting...';
    $response['redirect'] = 'index.php';
    $response['user_type'] = $user['user_type'];

} catch (Exception $e) {
    http_response_code(400);
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
