<?php
// ============================================================
//  ajax/get_journals.php  —  Return all journals
// ============================================================
require_once __DIR__ . '/../config/db.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // CORS fix for local dev

$categoryId = (int)($_GET['category_id'] ?? 0);
$search     = trim($_GET['q'] ?? '');

// ── is_active filter hataya — sab journals dikhao ─────────────
// (agar sirf active chahiye to: WHERE j.is_active = 1 add karo)
$sql    = "SELECT j.*, jc.name AS category_name
           FROM journals j
           LEFT JOIN journal_categories jc ON jc.category_id = j.category_id
           WHERE 1=1";
$params = [];

if ($categoryId) {
    $sql .= " AND j.category_id = ?";
    $params[] = $categoryId;
}
if ($search) {
    $sql .= " AND j.name LIKE ?";
    $params[] = '%' . $search . '%';
}
$sql .= " ORDER BY j.name ASC LIMIT 200";

try {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $journals = $stmt->fetchAll();
    
    // Debug: kitne journals mile
    jsonResponse(true, 'Found ' . count($journals) . ' journals', [
        'journals' => $journals,
        'count'    => count($journals),
    ]);
} catch (PDOException $e) {
    jsonResponse(false, 'DB error: ' . $e->getMessage());
}