<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';
require_once __DIR__ . '/../../includes/upload.php';

apply_cors();
$admin = require_admin();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

// GET    /templates.php              -> list (filter by category/channel/global)
// GET    /templates.php?id=5         -> single
// POST   /templates.php              -> create (admin preset, is_global=1). multipart if attachment included
// PUT    /templates.php?id=5         -> update
// PATCH  /templates.php?id=5&action=status -> enable/disable
// DELETE /templates.php?id=5         -> delete

if ($method === 'GET' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('SELECT * FROM templates WHERE id = :id');
    $stmt->execute([':id' => (int) $_GET['id']]);
    $row = $stmt->fetch();
    if (!$row) send_error('Template not found.', 404);
    send_success(['template' => $row]);
}

if ($method === 'GET') {
    [$page, $perPage, $offset] = paginate_params();
    $category = clean_str($_GET['category'] ?? '');
    $channel = clean_str($_GET['channel'] ?? '');
    $globalOnly = isset($_GET['global_only']) && $_GET['global_only'] === '1';

    $where = ['1=1'];
    $params = [];
    if ($category !== '') { $where[] = 'category = :category'; $params[':category'] = $category; }
    if ($channel !== '') { $where[] = 'channel = :channel'; $params[':channel'] = $channel; }
    if ($globalOnly) { $where[] = 'is_global = 1'; }

    $whereSql = implode(' AND ', $where);
    $count = $pdo->prepare("SELECT COUNT(*) FROM templates WHERE $whereSql");
    $count->execute($params);
    $total = (int) $count->fetchColumn();

    $stmt = $pdo->prepare(
        "SELECT * FROM templates WHERE $whereSql ORDER BY created_at DESC LIMIT :limit OFFSET :offset"
    );
    foreach ($params as $k => $v) $stmt->bindValue($k, $v);
    $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    send_success([
        'templates' => $stmt->fetchAll(),
        'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
    ]);
}

if ($method === 'POST') {
    // Support both JSON (no attachment) and multipart/form-data (with attachment file)
    $isMultipart = str_starts_with($_SERVER['CONTENT_TYPE'] ?? '', 'multipart/form-data');
    $input = $isMultipart ? $_POST : get_json_input();

    require_fields($input, ['title', 'message_text', 'event_type', 'channel']);

    $attachmentUrl = '';
    if ($isMultipart && isset($_FILES['attachment']) && $_FILES['attachment']['size'] > 0) {
        $attachmentUrl = handle_file_upload('attachment', 'templates', ALLOWED_DOC_TYPES);
    }

    $stmt = $pdo->prepare(
        'INSERT INTO templates (user_email, title, message_text, whatsapp_message_text, event_type, channel,
                                 category, media_type, link_url, attachment_url, call_button_number,
                                 location_text, notes, is_global, is_active)
         VALUES (:user_email, :title, :message_text, :wa_text, :event_type, :channel,
                 :category, :media_type, :link_url, :attachment_url, :call_number,
                 :location, :notes, 1, :is_active)'
    );
    $stmt->execute([
        ':user_email'  => 'ADMIN_PRESET',
        ':title'       => clean_str($input['title']),
        ':message_text' => clean_str($input['message_text']),
        ':wa_text'     => clean_str($input['whatsapp_message_text'] ?? $input['message_text']),
        ':event_type'  => clean_str($input['event_type']),
        ':channel'     => clean_str($input['channel']),
        ':category'    => clean_str($input['category'] ?? 'General'),
        ':media_type'  => clean_str($input['media_type'] ?? 'IMAGE'),
        ':link_url'    => clean_str($input['link_url'] ?? ''),
        ':attachment_url' => $attachmentUrl,
        ':call_number' => clean_str($input['call_button_number'] ?? ''),
        ':location'    => clean_str($input['location_text'] ?? ''),
        ':notes'       => clean_str($input['notes'] ?? ''),
        ':is_active'   => isset($input['is_active']) ? (int) (bool) $input['is_active'] : 1,
    ]);

    $newId = (int) $pdo->lastInsertId();
    log_admin_action($admin['email'], 'CREATE_TEMPLATE', 'template_id:' . $newId, '');
    send_success(['template_id' => $newId], 'Template created.', 201);
}

if ($method === 'PUT' && isset($_GET['id'])) {
    $id = (int) $_GET['id'];
    $input = get_json_input();

    $allowed = ['title', 'message_text', 'whatsapp_message_text', 'event_type', 'channel', 'category',
                'media_type', 'link_url', 'attachment_url', 'call_button_number', 'location_text', 'notes'];
    $fields = [];
    $params = [':id' => $id];
    foreach ($allowed as $f) {
        if (isset($input[$f])) {
            $fields[] = "$f = :$f";
            $params[":$f"] = clean_str($input[$f]);
        }
    }
    if (empty($fields)) send_error('No fields to update.', 422);

    $stmt = $pdo->prepare('UPDATE templates SET ' . implode(', ', $fields) . ' WHERE id = :id');
    $stmt->execute($params);

    log_admin_action($admin['email'], 'UPDATE_TEMPLATE', 'template_id:' . $id, '');
    send_success(null, 'Template updated.');
}

if ($method === 'PATCH' && isset($_GET['id']) && $action === 'status') {
    $id = (int) $_GET['id'];
    $input = get_json_input();
    require_fields($input, ['is_active']);

    $stmt = $pdo->prepare('UPDATE templates SET is_active = :active WHERE id = :id');
    $stmt->execute([':active' => $input['is_active'] ? 1 : 0, ':id' => $id]);

    log_admin_action($admin['email'], 'TOGGLE_TEMPLATE', 'template_id:' . $id, '');
    send_success(null, 'Template status updated.');
}

if ($method === 'DELETE' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('DELETE FROM templates WHERE id = :id');
    $stmt->execute([':id' => (int) $_GET['id']]);

    log_admin_action($admin['email'], 'DELETE_TEMPLATE', 'template_id:' . $_GET['id'], '');
    send_success(null, 'Template deleted.');
}

send_error('Invalid request.', 400);
