<?php
/**
 * Get XML Templates API
 * فوترة بلس - POS System
 * 
 * Retrieves XML invoice templates from the database
 */

require_once 'db.php';

// Only allow GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

try {
    global $pdo;
    
    // Get optional filters
    $sellerId = $_GET['seller_id'] ?? '';
    $templateType = $_GET['template_type'] ?? '';
    $isActive = isset($_GET['is_active']) ? $_GET['is_active'] : null;
    
    // Build query
    $sql = "SELECT * FROM xml_templates WHERE 1=1";
    $params = [];
    
    if (!empty($sellerId)) {
        $sql .= " AND seller_id = ?";
        $params[] = $sellerId;
    }
    
    if (!empty($templateType)) {
        $sql .= " AND template_type = ?";
        $params[] = $templateType;
    }
    
    if ($isActive !== null) {
        $sql .= " AND is_active = ?";
        $params[] = (int)$isActive;
    }
    
    $sql .= " ORDER BY template_type ASC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $templates = $stmt->fetchAll();
    
    jsonResponse(true, 'Templates retrieved', $templates);
    
} catch (PDOException $e) {
    jsonResponse(false, 'Failed to retrieve templates: ' . $e->getMessage(), null, 500);
}
?>
