<?php
require_once '../middleware.php';

header('Content-Type: application/json');

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

// Get admin token from headers
$admin_token = isset($_SERVER['HTTP_ADMIN_TOKEN']) ? $_SERVER['HTTP_ADMIN_TOKEN'] : '';

// Get query parameters
$action = isset($_GET['action']) ? $_GET['action'] : '';

// Authenticate admin
authenticateAdmin($admin_token);

$conn = getDbConnection();

if ($action === 'categories') {
    if ($method === 'GET') {
        // List all categories
        $query = "SELECT id, category_name, category_image_url, created_at FROM redeem_options_categories";
        $result = $conn->query($query);

        $categories = [];
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }

        sendResponse(200, 'Categories fetched', ['categories' => $categories]);
    } elseif ($method === 'POST') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        if (!$data || !isset($data['category_name']) || !isset($data['category_image_url'])) {
            sendResponse(400, 'Missing category_name or category_image_url');
        }

        $category_name = $data['category_name'];
        $category_image_url = $data['category_image_url'];

        $stmt = $conn->prepare("INSERT INTO redeem_options_categories (category_name, category_image_url) VALUES (?, ?)");
        $stmt->bind_param("ss", $category_name, $category_image_url);
        $stmt->execute();

        $stmt->close();
        sendResponse(200, 'Category created');
    } elseif ($method === 'PUT') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        if (!$data || !isset($data['category_id']) || !isset($data['category_name']) || !isset($data['category_image_url'])) {
            sendResponse(400, 'Missing category_id, category_name, or category_image_url');
        }

        $category_id = (int)$data['category_id'];
        $category_name = $data['category_name'];
        $category_image_url = $data['category_image_url'];

        $stmt = $conn->prepare("UPDATE redeem_options_categories SET category_name = ?, category_image_url = ? WHERE id = ?");
        $stmt->bind_param("ssi", $category_name, $category_image_url, $category_id);
        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            $stmt->close();
            sendResponse(400, 'Category not found');
        }

        $stmt->close();
        sendResponse(200, 'Category updated');
    } elseif ($method === 'DELETE') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        if (!$data || !isset($data['category_id'])) {
            sendResponse(400, 'Missing category_id');
        }

        $category_id = (int)$data['category_id'];
        $stmt = $conn->prepare("DELETE FROM redeem_options_categories WHERE id = ?");
        $stmt->bind_param("i", $category_id);
        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            $stmt->close();
            sendResponse(400, 'Category not found');
        }

        $stmt->close();
        sendResponse(200, 'Category deleted');
    } else {
        sendResponse(405, 'Method not allowed');
    }
} elseif ($action === 'subcategories') {
    if ($method === 'GET') {
        // List subcategories (optionally filter by category_id)
        $category_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0;
        if ($category_id > 0) {
            $query = "SELECT id, category_id, sub_category_name, sub_category_image_url, coins, cash, is_enabled, created_at 
                      FROM redeem_options_subcategories 
                      WHERE category_id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $category_id);
            $stmt->execute();
            $result = $stmt->get_result();
        } else {
            $query = "SELECT id, category_id, sub_category_name, sub_category_image_url, coins, cash, is_enabled, created_at 
                      FROM redeem_options_subcategories";
            $result = $conn->query($query);
        }

        $subcategories = [];
        while ($row = $result->fetch_assoc()) {
            $subcategories[] = $row;
        }

        if (isset($stmt)) $stmt->close();
        sendResponse(200, 'Subcategories fetched', ['subcategories' => $subcategories]);
    } elseif ($method === 'POST') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        if (!$data || !isset($data['category_id']) || !isset($data['sub_category_name']) || 
            !isset($data['sub_category_image_url']) || !isset($data['coins']) || !isset($data['cash'])) {
            sendResponse(400, 'Missing required fields');
        }

        $category_id = (int)$data['category_id'];
        $sub_category_name = $data['sub_category_name'];
        $sub_category_image_url = $data['sub_category_image_url'];
        $coins = (int)$data['coins'];
        $cash = (float)$data['cash'];
        $is_enabled = isset($data['is_enabled']) ? (int)$data['is_enabled'] : 1;

        // Verify category_id exists
        $stmt = $conn->prepare("SELECT id FROM redeem_options_categories WHERE id = ?");
        $stmt->bind_param("i", $category_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows === 0) {
            $stmt->close();
            sendResponse(400, 'Invalid category_id');
        }

        $stmt = $conn->prepare("INSERT INTO redeem_options_subcategories 
                                (category_id, sub_category_name, sub_category_image_url, coins, cash, is_enabled) 
                                VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("issidi", $category_id, $sub_category_name, $sub_category_image_url, $coins, $cash, $is_enabled);
        $stmt->execute();

        $stmt->close();
        sendResponse(200, 'Subcategory created');
    } elseif ($method === 'PUT') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        if (!$data || !isset($data['subcategory_id']) || !isset($data['sub_category_name']) || 
            !isset($data['sub_category_image_url']) || !isset($data['coins']) || !isset($data['cash'])) {
            sendResponse(400, 'Missing required fields');
        }

        $subcategory_id = (int)$data['subcategory_id'];
        $sub_category_name = $data['sub_category_name'];
        $sub_category_image_url = $data['sub_category_image_url'];
        $coins = (int)$data['coins'];
        $cash = (float)$data['cash'];
        $is_enabled = isset($data['is_enabled']) ? (int)$data['is_enabled'] : 1;

        $stmt = $conn->prepare("UPDATE redeem_options_subcategories 
                                SET sub_category_name = ?, sub_category_image_url = ?, coins = ?, cash = ?, is_enabled = ? 
                                WHERE id = ?");
        $stmt->bind_param("ssidi", $sub_category_name, $sub_category_image_url, $coins, $cash, $is_enabled, $subcategory_id);
        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            $stmt->close();
            sendResponse(400, 'Subcategory not found');
        }

        $stmt->close();
        sendResponse(200, 'Subcategory updated');
    } elseif ($method === 'DELETE') {
        // Get the encrypted payload
        $encrypted_payload = file_get_contents('php://input');
        if (empty($encrypted_payload)) {
            sendResponse(400, 'Empty request body');
        }

        // Decrypt the payload
        $data = decryptRequestPayload($encrypted_payload);
        if (!$data) {
            sendResponse(400, 'Invalid request body');
        }

        if (!$data || !isset($data['subcategory_id'])) {
            sendResponse(400, 'Missing subcategory_id');
        }

        $subcategory_id = (int)$data['subcategory_id'];
        $stmt = $conn->prepare("DELETE FROM redeem_options_subcategories WHERE id = ?");
        $stmt->bind_param("i", $subcategory_id);
        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            $stmt->close();
            sendResponse(400, 'Subcategory not found');
        }

        $stmt->close();
        sendResponse(200, 'Subcategory deleted');
    } else {
        sendResponse(405, 'Method not allowed');
    }
} else {
    sendResponse(400, 'Invalid action');
}

$conn->close();
?>