<?php
/**
 * ============================================================
 * AJAX: User Login
 * ============================================================
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be POST
if (!isPost()) {
    Response::error('Invalid request', [], 400);
}

// Validate CSRF
if (!csrf_validate()) {
    Response::csrfError();
}

// Get credentials
$email = sanitize(post('email'));
$password = post('password');
$remember = post('remember') ? true : false;

// Validate
$validator = Validator::make($_POST);
$validator->required('email', 'ইমেইল')
          ->email('email')
          ->required('password', 'পাসওয়ার্ড');

if ($validator->fails()) {
    Response::validationError($validator->errors());
}

// Find user
$user = Database::fetchOne(
    "SELECT id, full_name, email, password_hash, is_blocked FROM users WHERE email = ?",
    [$email]
);

if (!$user) {
    Response::error('ইমেইল বা পাসওয়ার্ড ভুল');
}

// Check if blocked
if ($user['is_blocked']) {
    Response::error('আপনার অ্যাকাউন্ট ব্লক করা হয়েছে। সাপোর্টে যোগাযোগ করুন।');
}

// Verify password
if (!password_verify($password, $user['password_hash'])) {
    Response::error('ইমেইল বা পাসওয়ার্ড ভুল');
}

// Set session
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['full_name'];
$_SESSION['user_email'] = $user['email'];
$_SESSION['last_activity'] = time();

// Merge guest cart with user cart if exists
require_once APP_PATH . '/services/cart_service.php';
$cartService = new CartService();

// Get redirect URL
$redirect = $_SESSION['intended_url'] ?? url('public/');
unset($_SESSION['intended_url']);

Response::success('সফলভাবে লগইন হয়েছে। স্বাগতম, ' . $user['full_name'] . '!', [
    'redirect' => $redirect
]);
