<?php
include_once '../../config/root_path.php';
require_once ROOT_PATH . 'admin/backend/init.php';
/**
 * EMAIL TEMPLATE VIEWER - PARTICIPATION STATUS
 * Untuk debug & preview email template participation status
 * 
 * http://192.168.1.167:8080/padel/api/mail_templates/viewer/preview_participation.php?lang=en&template=participation_status_accepted
 * http://192.168.1.167:8080/padel/api/mail_templates/viewer/preview_participation.php?lang=id&template=participation_status_rejected
 * 
 * Untuk testing cancelled: 
 * http://192.168.1.167:8080/padel/api/mail_templates/viewer/preview_participation.php?lang=id&template=participation_status_rejected&status=cancelled
 * 
 * Untuk testing disqualified:
 * http://192.168.1.167:8080/padel/api/mail_templates/viewer/preview_participation.php?lang=id&template=participation_status_rejected&status=disqualified
 */

// =============================
// CONFIG
// =============================
$basePath = ROOT_PATH . '/api/mail_templates';
$lang     = $_GET['lang'] ?? 'id';
$template = $_GET['template'] ?? 'participation_status_accepted';
$status   = $_GET['status'] ?? 'cancelled'; // cancelled or disqualified

// =============================
// PATH RESOLUTION
// =============================
$headerFile   = $basePath . '/partials/header.html';
$footerFile   = $basePath . '/partials/footer.html';
$bodyFile     = $basePath . '/' . $lang . '/' . $template . '.html';

// fallback language
if (!file_exists($bodyFile)) {
    $lang = 'id';
    $bodyFile = $basePath . '/id/' . $template . '.html';
}

// =============================
// VALIDATION
// =============================
if (!file_exists($headerFile) || !file_exists($footerFile) || !file_exists($bodyFile)) {
    echo "<h3>Template tidak ditemukan</h3>";
    echo "<pre>
Lang      : {$lang}
Template  : {$template}
</pre>";
    exit;
}

// =============================
// LOAD FILES
// =============================
$header = file_get_contents($headerFile);
$body   = file_get_contents($bodyFile);
$footer = file_get_contents($footerFile);
$verifyUrl = "{$domain_host}/api/public/verify-email.php?token=xxx";

// =============================
// DUMMY DATA
// =============================

// Tournament Data
$TournamentData = [
    'NamaTournament' => 'Padel Open Championship 2025',
    'Lokasi' => 'Padel Arena, Jakarta Selatan',
    'Gambar' => 'https://pbpisumut.com/admin/attachments/tournament/12/12_gambar_17828913163727.jpeg',
    'Tanggal' => '15-20 Desember 2025',
    'URLLanding' => 'https://pbpisumut.com/event/12'
];

// Team Data
$TeamData = [
    'NamaTim' => 'Padel Warriors',
    'Kategori' => 'Double Putra',
    'Level' => 'Intermediate',
    'Partner1' => [
        'Nama' => 'Budi Hartono',
        'Email' => 'budi.hartono@email.com'
    ],
    'Partner2' => [
        'Nama' => 'Andi Wijaya',
        'Email' => 'andi.wijaya@email.com'
    ]
];

// Status mapping
$statusMapping = [
    'cancelled' => [
        'id' => 'Dibatalkan',
        'en' => 'Cancelled',
        'text_id' => 'dibatalkan',
        'text_en' => 'cancelled'
    ],
    'disqualified' => [
        'id' => 'Didiskualifikasi',
        'en' => 'Disqualified',
        'text_id' => 'didiskualifikasi',
        'text_en' => 'disqualified'
    ]
];

$statusData = $statusMapping[$status] ?? $statusMapping['cancelled'];

$dummyData = [
    'LogoURL'            => 'https://pbpisumut.com/public/padel_logo.jpeg',
    'CompanyName'        => 'Padel Indonesia',
    'CompanyAddress'     => 'Jl. Contoh No. 123, Jakarta Selatan 12345',
    'CompanyPhone'       => '+62 812-3456-7890',
    'CompanyEmail'       => 'info@padelindonesia.com',
    'CompanyWhatsapp'    => '6281234567890',
    'CompanyWhatsappDisplay' => '+62 8123 4567 890',
    'CurrentYear'        => date('Y'),
    
    // User Data
    'NamaLengkap'        => 'Budi Hartono',
    'Email'              => 'budi.hartono@email.com',
    'NoTelp'             => '08123456789',
    
    // Tournament Data
    'Tournament'         => $TournamentData,
    
    // Team Data
    'TeamData'           => $TeamData,
    
    // Status Data
    'StatusPartisipasi' => ($lang == 'id') ? $statusData['id'] : $statusData['en'],
    'StatusPartisipasiText' => ($lang == 'id') ? $statusData['text_id'] : $statusData['text_en'],
    
    // Rejection Reason
    'AlasanDitolak'      => ($lang == 'id') 
        ? 'Tim tidak memenuhi persyaratan yang ditentukan. Mohon periksa kembali persyaratan pendaftaran.' 
        : 'Team does not meet the specified requirements. Please review the registration requirements.'
];

// =============================
// REPLACE PLACEHOLDER
// =============================
function applyParams(string $html, array $params): string {
    // Handle nested arrays (Tournament, TeamData)
    foreach ($params as $key => $value) {
        if (is_array($value)) {
            // For tournament data
            if ($key === 'Tournament') {
                foreach ($value as $subKey => $subValue) {
                    $html = str_replace('{{ Tournament.' . $subKey . ' }}', $subValue, $html);
                }
            }
            // For team data
            elseif ($key === 'TeamData') {
                foreach ($value as $subKey => $subValue) {
                    if (is_array($subValue)) {
                        foreach ($subValue as $subSubKey => $subSubValue) {
                            $html = str_replace('{{ TeamData.' . $subKey . '.' . $subSubKey . ' }}', $subSubValue, $html);
                        }
                    } else {
                        $html = str_replace('{{ TeamData.' . $subKey . ' }}', $subValue, $html);
                    }
                }
            }
        } else {
            // Simple replacements
            $html = str_replace('{{ ' . $key . ' }}', $value, $html);
        }
    }
    
    // Handle conditional blocks (simple remove if condition not met)
    // For image: if Tournament.Gambar exists
    if (!isset($params['Tournament']['Gambar']) || empty($params['Tournament']['Gambar'])) {
        $html = preg_replace('/{% if Tournament\.Gambar %}.*?{% endif %}/s', '', $html);
    } else {
        $html = preg_replace('/{% if Tournament\.Gambar %}(.*?){% endif %}/s', '$1', $html);
    }
    
    return $html;
}

// =============================
// RENDER
// =============================
$output = $header . $body . $footer;
$output = applyParams($output, $dummyData);

// =============================
// OUTPUT
// =============================
echo $output;
?>