<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db.php';

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

header('Content-Type: application/json; charset=utf-8');

try {
    $pdo = db();
    $raw = file_get_contents('php://input');
    $data = json_decode($raw ?: '{}', true) ?: [];

    $pageUrl = trim((string)($data['page_url'] ?? ''));
    $pageTitle = trim((string)($data['page_title'] ?? ''));
    $userId = (int)($_SESSION['user_id'] ?? 0);

    if ($userId <= 0 || $pageUrl === '') {
        http_response_code(422);
        echo json_encode(['ok' => false, 'message' => 'بيانات غير صالحة'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $tableExistsStmt = $pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'user_favorites' LIMIT 1");
    if (!(bool)($tableExistsStmt ? $tableExistsStmt->fetchColumn() : false)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'message' => 'جدول المفضلة غير موجود. نفذ ملف SQL أولاً.'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $normalizedUrl = rtrim(parse_url($pageUrl, PHP_URL_PATH) ?: $pageUrl, '/');
    if ($normalizedUrl === '') {
        $normalizedUrl = '/';
    }

    $check = $pdo->prepare("SELECT id FROM user_favorites WHERE user_id=? AND page_url=? LIMIT 1");
    $check->execute([$userId, $normalizedUrl]);
    $existingId = (int)($check->fetchColumn() ?: 0);

    if ($existingId > 0) {
        $del = $pdo->prepare("DELETE FROM user_favorites WHERE id=? AND user_id=?");
        $del->execute([$existingId, $userId]);
        echo json_encode(['ok' => true, 'active' => false], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $ins = $pdo->prepare("INSERT INTO user_favorites (user_id, page_url, page_title, created_at) VALUES (?, ?, ?, NOW())");
    $ins->execute([$userId, $normalizedUrl, $pageTitle !== '' ? $pageTitle : $normalizedUrl]);

    echo json_encode(['ok' => true, 'active' => true], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
