<?php
/**
 * Update XML Template API
 * فوترة بلس - POS System
 * 
 * Updates an XML invoice template in the database
 */

require_once 'db.php';
require_once 'auth.php';

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

$input = getJsonInput();

// Validate required fields
if (empty($input['template_id'])) {
    jsonResponse(false, 'template_id is required', null, 400);
}

if (!isset($input['template_content'])) {
    jsonResponse(false, 'template_content is required', null, 400);
}

$templateId = $input['template_id'];
$templateContent = $input['template_content'];

try {
    global $pdo;
    
    // Check if template exists
    $stmt = $pdo->prepare("SELECT * FROM xml_templates WHERE id = ? LIMIT 1");
    $stmt->execute([$templateId]);
    $existing = $stmt->fetch();
    
    if (!$existing) {
        jsonResponse(false, 'Template not found', null, 404);
    }
    
    // Update template
    $stmt = $pdo->prepare("
        UPDATE xml_templates 
        SET template_content = ?, 
            updated_at = ?
        WHERE id = ?
    ");
    $stmt->execute([
        $templateContent,
        getCurrentTimestamp(),
        $templateId
    ]);
    
    // Return updated template
    $stmt = $pdo->prepare("SELECT * FROM xml_templates WHERE id = ? LIMIT 1");
    $stmt->execute([$templateId]);
    $updated = $stmt->fetch();
    
    jsonResponse(true, 'Template updated successfully', $updated);
    
} catch (PDOException $e) {
    jsonResponse(false, 'Failed to update template: ' . $e->getMessage(), null, 500);
}
?>
