<?php
header('Content-Type: application/json; charset=utf-8');

$host = 'localhost';
$db   = 'porihoqu_ticket';
$user = 'porihoqu_ticket';
$pass = ']78P*%Dt5^FVRf2B';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Create table if not exists
$pdo->exec("CREATE TABLE IF NOT EXISTS sms_templates (
    id INT AUTO_INCREMENT PRIMARY KEY,
    `key` VARCHAR(100) NOT NULL UNIQUE,
    template TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // GET all templates
    $stmt = $pdo->query("SELECT id, `key`, template FROM sms_templates ORDER BY id ASC");
    $templates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($templates);
    exit;
}

if ($method === 'POST') {
    $action = $_POST['action'] ?? '';

    // ADD
    if ($action === 'add') {
        $key      = trim($_POST['key'] ?? '');
        $template = trim($_POST['template'] ?? '');

        if ($key === '' || $template === '') {
            echo json_encode(['status' => 'error', 'message' => 'key and template are required']);
            exit;
        }

        $check = $pdo->prepare("SELECT id FROM sms_templates WHERE `key` = ?");
        $check->execute([$key]);
        if ($check->fetch()) {
            echo json_encode(['status' => 'error', 'message' => 'Template key already exists']);
            exit;
        }

        $stmt = $pdo->prepare("INSERT INTO sms_templates (`key`, template) VALUES (?, ?)");
        $stmt->execute([$key, $template]);

        echo json_encode(['status' => 'success', 'message' => 'Template added', 'id' => $pdo->lastInsertId()]);
        exit;
    }

    // EDIT
    if ($action === 'edit') {
        $id       = $_POST['id'] ?? '';
        $key      = trim($_POST['key'] ?? '');
        $template = trim($_POST['template'] ?? '');

        if ($id === '' || $key === '' || $template === '') {
            echo json_encode(['status' => 'error', 'message' => 'id, key and template are required']);
            exit;
        }

        $stmt = $pdo->prepare("UPDATE sms_templates SET `key` = ?, template = ? WHERE id = ?");
        $stmt->execute([$key, $template, $id]);

        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Template updated']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Template not found or no changes']);
        }
        exit;
    }

    // DELETE
    if ($action === 'delete') {
        $id = $_POST['id'] ?? '';

        if ($id === '') {
            echo json_encode(['status' => 'error', 'message' => 'id is required']);
            exit;
        }

        $stmt = $pdo->prepare("DELETE FROM sms_templates WHERE id = ?");
        $stmt->execute([$id]);

        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Template deleted']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Template not found']);
        }
        exit;
    }

    echo json_encode(['status' => 'error', 'message' => 'Invalid action. Use: add, edit, delete']);
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
