<?php
require_once __DIR__ . '/../includes/config.php';
session_start_secure();
header('Content-Type: application/json; charset=utf-8');

$action = sanitize_str($_POST['action'] ?? $_GET['action'] ?? '');

match ($action) {
    'login'    => handle_login(),
    'register' => handle_register(),
    'logout'   => handle_logout(),
    default    => json_response(['error' => 'Unknown action'], 400),
};

function handle_login(): void {
    $phone = sanitize_str($_POST['phone'] ?? '');
    $pass  = $_POST['password'] ?? '';

    if (strlen($phone) !== 10 || !$pass) {
        json_response(['error' => 'بيانات غير صحيحة'], 422);
    }

    $stmt = db()->prepare(
        "SELECT id, name, role, password_hash, lang_pref, theme_pref, is_active
         FROM baitari_users WHERE phone = :phone LIMIT 1"
    );
    $stmt->execute([':phone' => $phone]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($pass, $user['password_hash'])) {
        json_response(['error' => 'رقم الهاتف أو كلمة المرور غير صحيحة'], 401);
    }
    if (!$user['is_active']) {
        json_response(['error' => 'الحساب موقوف. تواصل مع الدعم'], 403);
    }

    // Set session
    $_SESSION['user'] = [
        'id'        => $user['id'],
        'name'      => $user['name'],
        'role'      => $user['role'],
        'lang_pref' => $user['lang_pref'],
        'theme_pref'=> $user['theme_pref'],
    ];

    // Update last_login
    db()->prepare("UPDATE baitari_users SET last_login=NOW() WHERE id=:id")
       ->execute([':id' => $user['id']]);

    json_response([
        'success'  => true,
        'role'     => $user['role'],
        'redirect' => match($user['role']) {
            'admin' => '/pages/admin.php',
            'vet'   => '/index.php',
            default => '/index.php',
        },
    ]);
}

function handle_register(): void {
    $name  = sanitize_str($_POST['name']  ?? '');
    $phone = sanitize_str($_POST['phone'] ?? '');
    $email = sanitize_str($_POST['email'] ?? '');
    $pass  = $_POST['password'] ?? '';
    $role  = sanitize_str($_POST['role']  ?? 'pet_owner');
    $wilaya= sanitize_str($_POST['wilaya']?? '');

    if (!$name || strlen($phone) !== 10 || strlen($pass) < 8) {
        json_response(['error' => 'بيانات غير مكتملة'], 422);
    }

    // Check phone uniqueness
    $exists = db()->prepare("SELECT id FROM baitari_users WHERE phone=:p LIMIT 1");
    $exists->execute([':p' => $phone]);
    if ($exists->fetch()) {
        json_response(['error' => 'رقم الهاتف مسجّل بالفعل'], 409);
    }

    $hash = password_hash($pass, PASSWORD_BCRYPT, ['cost' => 12]);
    $stmt = db()->prepare(
        "INSERT INTO baitari_users (name, phone, email, password_hash, role, wilaya)
         VALUES (:name, :phone, :email, :hash, :role, :wilaya)"
    );
    $stmt->execute([
        ':name'   => $name,
        ':phone'  => $phone,
        ':email'  => $email ?: null,
        ':hash'   => $hash,
        ':role'   => in_array($role, ['pet_owner','farm_owner','vet']) ? $role : 'pet_owner',
        ':wilaya' => $wilaya ?: null,
    ]);
    $uid = db()->lastInsertId();

    // If vet, create pending profile
    if ($role === 'vet') {
        db()->prepare(
            "INSERT INTO baitari_vet_profiles (vet_id, license_no, is_verified)
             VALUES (:vid, :lic, 0)"
        )->execute([
            ':vid' => $uid,
            ':lic' => sanitize_str($_POST['license'] ?? 'PENDING'),
        ]);
        json_response(['success' => true, 'pending' => true, 'message' => 'طلبك قيد المراجعة']);
    }

    // Auto-login
    $_SESSION['user'] = [
        'id'   => $uid, 'name' => $name,
        'role' => $role, 'lang_pref' => 'ar', 'theme_pref' => 'light',
    ];
    json_response(['success' => true, 'role' => $role, 'redirect' => '/index.php']);
}

function handle_logout(): void {
    session_start_secure();
    $_SESSION = [];
    session_destroy();
    json_response(['success' => true, 'redirect' => '/login.php']);
}
