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

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

// GET    /templates.php                    -> own templates + global presets, filterable
// GET    /templates.php?id=5                -> single (must be own or global)
// POST   /templates.php                     -> create own template (multipart if attachment)
// PUT    /templates.php?id=5                -> update own template
// PATCH  /templates.php?id=5&action=favorite -> toggle favorite
// PATCH  /templates.php?id=5&action=status   -> enable/disable
// DELETE /templates.php?id=5                -> delete own template

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

if ($method === 'GET') {
    $category = clean_str($_GET['category'] ?? '');
    $channel = clean_str($_GET['channel'] ?? '');
    $favoritesOnly = ($_GET['favorites_only'] ?? '') === '1';

    $where = ['(user_email = :email OR is_global = 1)'];
    $params = [':email' => $authUser['email']];
    if ($category !== '') { $where[] = 'category = :category'; $params[':category'] = $category; }
    if ($channel !== '') { $where[] = 'channel = :channel'; $params[':channel'] = $channel; }
    if ($favoritesOnly) { $where[] = 'is_favorite = 1'; }

    $whereSql = implode(' AND ', $where);
    $stmt = $pdo->prepare("SELECT * FROM templates WHERE $whereSql ORDER BY is_global ASC, created_at DESC");
    $stmt->execute($params);

    send_success(['templates' => $stmt->fetchAll()]);
}

if ($method === 'POST') {
    $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, 0, 1)'
    );
    $stmt->execute([
        ':user_email'  => $authUser['email'],
        ':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'] ?? ''),
    ]);

    send_success(['template_id' => (int) $pdo->lastInsertId()], '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, ':email' => $authUser['email']];
    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 AND user_email = :email');
    $stmt->execute($params);

    if ($stmt->rowCount() === 0) send_error('Template not found or not editable.', 404);
    send_success(null, 'Template updated.');
}

if ($method === 'PATCH' && isset($_GET['id']) && $action === 'favorite') {
    $input = get_json_input();
    require_fields($input, ['is_favorite']);
    $stmt = $pdo->prepare('UPDATE templates SET is_favorite = :fav WHERE id = :id AND user_email = :email');
    $stmt->execute([':fav' => $input['is_favorite'] ? 1 : 0, ':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    send_success(null, 'Favorite updated.');
}

if ($method === 'PATCH' && isset($_GET['id']) && $action === 'status') {
    $input = get_json_input();
    require_fields($input, ['is_active']);
    $stmt = $pdo->prepare('UPDATE templates SET is_active = :active WHERE id = :id AND user_email = :email');
    $stmt->execute([':active' => $input['is_active'] ? 1 : 0, ':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    send_success(null, 'Status updated.');
}

if ($method === 'DELETE' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('DELETE FROM templates WHERE id = :id AND user_email = :email');
    $stmt->execute([':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    if ($stmt->rowCount() === 0) send_error('Template not found or not deletable.', 404);
    send_success(null, 'Template deleted.');
}

send_error('Invalid request.', 400);
