<?php
require_once '../config/database.php';
require_once '../includes/company_config.php';
secureSessionStart();
requireLogin();

header('Content-Type: application/json');

$conn = getConnection();
$company = getCompanyDetails($conn);

// Check if table exists
$table_check = mysqli_query($conn, "SHOW TABLES LIKE 'email_templates'");
if (mysqli_num_rows($table_check) == 0) {
    // Create table first
    $create_table = "CREATE TABLE IF NOT EXISTS `email_templates` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `title` varchar(255) NOT NULL,
        `subject` varchar(255) NOT NULL,
        `content` text NOT NULL,
        `category` varchar(50) DEFAULT 'general',
        `created_by` int(11) DEFAULT NULL,
        `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
        `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        KEY `category` (`category`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
    
    mysqli_query($conn, $create_table);
}

// Insert default templates with company name placeholder
$templates = [
    [
        'title' => 'Welcome Message',
        'subject' => 'Welcome to {company_name}!',
        'content' => "Dear {user_name},\n\nWelcome to {company_name}! We're excited to have you on board.\n\nYour account has been successfully created with User ID: {user_id}\n\nBest regards,\n{company_name} Team",
        'category' => 'welcome'
    ],
    [
        'title' => 'Thank You',
        'subject' => 'Thank You from {company_name}',
        'content' => "Dear {user_name},\n\nThank you for being a valued member of {company_name}.\n\nWe appreciate your trust in us.\n\nBest regards,\n{company_name} Team",
        'category' => 'general'
    ],
    [
        'title' => 'Account Updated',
        'subject' => 'Account Updated Successfully',
        'content' => "Dear {user_name},\n\nYour account details have been successfully updated on {date}.\n\nIf you did not make these changes, please contact {company_name} support immediately.\n\nBest regards,\n{company_name} Team",
        'category' => 'account'
    ],
    [
        'title' => 'KYC Verification',
        'subject' => 'KYC Verification Required',
        'content' => "Dear {user_name},\n\nPlease complete your KYC verification to continue using all features of {company_name}.\n\nRequired documents:\n- PAN Card\n- Aadhaar Card\n- Bank Details\n\nUpload documents in your profile.\n\nBest regards,\n{company_name} Team",
        'category' => 'kyc'
    ],
    [
        'title' => 'Withdrawal Processed',
        'subject' => 'Withdrawal Processed Successfully',
        'content' => "Dear {user_name},\n\nYour withdrawal request has been processed successfully by {company_name}.\n\nAmount: ₹{amount}\nDate: {date}\n\nIt will reflect in your account within 2-3 business days.\n\nBest regards,\n{company_name} Team",
        'category' => 'withdrawal'
    ],
    [
        'title' => 'PIN Generated',
        'subject' => 'PIN Generated Successfully',
        'content' => "Dear {user_name},\n\nYour E-PIN has been generated successfully by {company_name}.\n\nPIN: {pin}\nAmount: ₹{amount}\n\nUse this PIN for registration.\n\nBest regards,\n{company_name} Team",
        'category' => 'pin'
    ],
    [
        'title' => 'Support Response',
        'subject' => 'Support Ticket Update',
        'content' => "Dear {user_name},\n\nYour support ticket #{ticket_id} has been updated.\n\nOur team at {company_name} has responded to your query. Please check your support center for details.\n\nBest regards,\n{company_name} Support Team",
        'category' => 'support'
    ],
    [
        'title' => 'Promotional Offer',
        'subject' => 'Special Offer from {company_name}!',
        'content' => "Dear {user_name},\n\n{company_name} has an exclusive offer for you!\n\nJoin our special promotion and earn extra rewards.\n\nOffer valid until {date}\n\nBest regards,\n{company_name} Team",
        'category' => 'promo'
    ]
];

$success = true;
$errors = [];

foreach ($templates as $template) {
    $title = mysqli_real_escape_string($conn, $template['title']);
    $subject = mysqli_real_escape_string($conn, $template['subject']);
    $content = mysqli_real_escape_string($conn, $template['content']);
    $category = mysqli_real_escape_string($conn, $template['category']);
    
    // Check if template already exists
    $check = mysqli_query($conn, "SELECT id FROM email_templates WHERE title = '$title'");
    if (mysqli_num_rows($check) == 0) {
        $query = "INSERT INTO email_templates (title, subject, content, category) 
                  VALUES ('$title', '$subject', '$content', '$category')";
        if (!mysqli_query($conn, $query)) {
            $success = false;
            $errors[] = mysqli_error($conn);
        }
    }
}

if ($success) {
    echo json_encode(['success' => true, 'message' => 'Templates created successfully']);
} else {
    echo json_encode(['success' => false, 'error' => implode(', ', $errors)]);
}
exit();
?>