<?php
require_once __DIR__ . '/config.php';

session_start();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

if ($method === 'OPTIONS') {
    http_response_code(200);
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    exit;
}

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

if ($action === 'login' && $method === 'POST') {
    $input = getInput();
    $email = trim($input['email'] ?? '');
    $password = $input['password'] ?? '';

    if (empty($email) || empty($password)) {
        jsonResponse(['success' => false, 'error' => 'Email and password are required']);
    }

    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE email = ? AND is_active = 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        unset($user['password_hash']);
        $_SESSION['crm_user'] = $user;
        logActivity($user['id'], 'login', 'user', $user['id'], 'User logged in');
        jsonResponse(['success' => true, 'user' => $user]);
    } else {
        jsonResponse(['success' => false, 'error' => 'Invalid email or password'], 401);
    }
}

if ($action === 'logout') {
    if (isset($_SESSION['crm_user'])) {
        logActivity($_SESSION['crm_user']['id'], 'logout', 'user', $_SESSION['crm_user']['id'], 'User logged out');
    }
    session_destroy();
    jsonResponse(['success' => true, 'message' => 'Logged out successfully']);
}

if ($action === 'check') {
    if (isset($_SESSION['crm_user'])) {
        jsonResponse(['success' => true, 'user' => $_SESSION['crm_user']]);
    } else {
        jsonResponse(['success' => false, 'error' => 'Not logged in'], 401);
    }
}

if ($action === 'change_password' && $method === 'POST') {
    $currentUser = requireAuth();
    $input = getInput();
    $currentPass = $input['current_password'] ?? '';
    $newPass = $input['new_password'] ?? '';

    if (strlen($newPass) < 6) {
        jsonResponse(['success' => false, 'error' => 'Password must be at least 6 characters']);
    }

    $db = getDB();
    $stmt = $db->prepare("SELECT password_hash FROM users WHERE id = ?");
    $stmt->execute([$currentUser['id']]);
    $row = $stmt->fetch();

    if (!$row || !password_verify($currentPass, $row['password_hash'])) {
        jsonResponse(['success' => false, 'error' => 'Current password is incorrect']);
    }

    $newHash = password_hash($newPass, PASSWORD_BCRYPT);
    $db->prepare("UPDATE users SET password_hash = ? WHERE id = ?")->execute([$newHash, $currentUser['id']]);
    jsonResponse(['success' => true, 'message' => 'Password changed successfully']);
}

jsonResponse(['success' => false, 'error' => 'Unknown action'], 400);
