<?php
session_start();
include "connection.php";
include "validation.php";

header("Content-Type: application/json");                     
$response = [
    "status" => false,
    "message" => "",
    "data" => []
];

try {
    $search = $_GET['search'] ?? '';
    $category_id = $_GET['category_id'] ?? '';
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $items_per_page = 6; // Show 6 categories per page
    $offset = ($page - 1) * $items_per_page;
    
    // Build the base query to count total records
    $count_query = "SELECT COUNT(*) as total FROM `category` WHERE 1=1";
    $query = "SELECT * FROM `category` WHERE 1=1";
    $params = [];
    $types = "";
    
    // Add search condition
    if (!empty($search)) {
        $search_condition = " AND (`title` LIKE ? OR `description` LIKE ?)";
        $count_query .= $search_condition;
        $query .= $search_condition;
        $searchParam = "%" . $search . "%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $types .= "ss";
    }
    
    // Add category filter condition
    if (!empty($category_id) && is_numeric($category_id)) {
        $category_condition = " AND `id` = ?";
        $count_query .= $category_condition;
        $query .= $category_condition;
        $params[] = $category_id;
        $types .= "i";
    }
    
    // Get total count
    if (!empty($params)) {
        Database::setUpConnection();
        $stmt = Database::$connection->prepare($count_query);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $count_result = $stmt->get_result();
        $total_count = $count_result->fetch_assoc()['total'];
    } else {
        $count_result = Database::search($count_query);
        $total_count = $count_result->fetch_assoc()['total'];
    }
    
    // Calculate total pages
    $total_pages = ceil($total_count / $items_per_page);
    
    // Add pagination and ordering to main query
    $query .= " ORDER BY `id` DESC LIMIT ? OFFSET ?";
    
    // Execute main query with parameters
    if (!empty($params)) {
        Database::setUpConnection();
        $stmt = Database::$connection->prepare($query);
        $params[] = $items_per_page;
        $params[] = $offset;
        $types .= "ii";
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $category_rs = $stmt->get_result();
    } else {
        $query_with_pagination = $query;
        Database::setUpConnection();
        $stmt = Database::$connection->prepare($query_with_pagination);
        $stmt->bind_param("ii", $items_per_page, $offset);
        $stmt->execute();
        $category_rs = $stmt->get_result();
    }
    
    if ($category_rs->num_rows > 0) {
        $categories = [];
        while ($category = $category_rs->fetch_assoc()) {
            $categories[] = [
                "id" => $category["id"],
                "title" => $category["title"],
                "description" => $category["description"],
                "img_path" => $category["img_path"]
            ];
        }
        
        $response["status"] = true;
        $response["data"] = $categories;
        $response["total_pages"] = $total_pages;
        $response["message"] = "Categories loaded successfully";
    } else {
        $response["status"] = true;
        $response["message"] = "No categories found";
        $response["data"] = [];
        $response["total_pages"] = 0;
    }
    
} catch (Exception $e) {
    $response["status"] = false;
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
exit;
?>
