<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__.'/../inc/config.php';
require_once __DIR__.'/../inc/db.php';
require_once __DIR__.'/../inc/helpers.php';

// Sekuriti: Pastikan hanya admin yang log masuk boleh akses
if(empty($_SESSION['admin_id'])){ header('Location: login.php'); exit; }
if ($_SESSION['admin_role'] !== 'admin') {
    exit('Akses disekat. Anda tiada kebenaran untuk melihat halaman ini.');
}

// --- PENGUMPULAN DATA AUTOMATIK (30 HARI TERAKHIR) ---
$days_period = 30;
$paid_filter = "WHERE status IN ('Paid', 'Shipped') AND created_at >= date('now', '-{$days_period} days')";

// Data Jualan Asas
$sales_data = db()->query("SELECT IFNULL(SUM(amount),0) as s, COUNT(id) as c FROM orders {$paid_filter}")->fetch();
$total_sales = (float)$sales_data['s'];
$total_orders = (int)$sales_data['c'];
$aov = $total_orders > 0 ? $total_sales / $total_orders : 0;

// Pakej Terlaris
$best_pkg_q = db()->query("SELECT package_name, COUNT(id) as c FROM orders {$paid_filter} GROUP BY package_name ORDER BY c DESC LIMIT 1")->fetch();
$best_package = $best_pkg_q ? $best_pkg_q['package_name'] . " ({$best_pkg_q['c']} pesanan)" : "Tiada jualan";

// Profil Pelanggan Terbanyak
$top_profile_q = db()->query("SELECT purchase_purpose, COUNT(id) as c FROM orders {$paid_filter} AND purchase_purpose IS NOT NULL AND purchase_purpose != '' GROUP BY purchase_purpose ORDER BY c DESC LIMIT 1")->fetch();
$top_profile = $top_profile_q ? $top_profile_q['purchase_purpose'] : "Tidak dinyatakan";

// Kadar 'Order Bump'
$bump_data = db()->query("SELECT SUM(order_bump) as bumps, COUNT(id) as total FROM orders {$paid_filter}")->fetch();
$bump_rate = $bump_data['total'] > 0 ? round(($bump_data['bumps'] / $bump_data['total']) * 100, 1) : 0;

// Data Ujian A/B (Keseluruhan)
$visits_a = (int)db()->query("SELECT COUNT(id) as c FROM visits WHERE ab_variant = 'a'")->fetch()['c'];
$sales_a = (int)db()->query("SELECT COUNT(id) as c FROM orders WHERE status IN ('Paid','Shipped') AND ab_variant = 'a'")->fetch()['c'];
$cvr_a = $visits_a > 0 ? round(($sales_a / $visits_a) * 100, 2) : 0;
$visits_b = (int)db()->query("SELECT COUNT(id) as c FROM visits WHERE ab_variant = 'b'")->fetch()['c'];
$sales_b = (int)db()->query("SELECT COUNT(id) as c FROM orders WHERE status IN ('Paid','Shipped') AND ab_variant = 'b'")->fetch()['c'];
$cvr_b = $visits_b > 0 ? round(($sales_b / $visits_b) * 100, 2) : 0;
$headline_a_text = setting('headline_a');
$headline_b_text = setting('headline_b');
$winner = ($cvr_a > $cvr_b) ? 'A' : (($cvr_b > $cvr_a) ? 'B' : 'Seri');

// Data Laporan UTM Terperinci
$utm_breakdown = db()->query("
    SELECT utm_source, SUM(amount) as total_sales, COUNT(id) as total_orders
    FROM orders
    {$paid_filter} AND utm_source IS NOT NULL AND utm_source != ''
    GROUP BY utm_source ORDER BY total_sales DESC
")->fetchAll();
$website_url = setting('MAIN_WEBSITE_URL', 'https://vanillablue.mymukmin.com');


// --- SEDIAKAN TEKS LENGKAP UNTUK AI ---
$report_text = "Analisis data perniagaan dari laman web " . $website_url . "\n\n";
$report_text .= "### DATA JUALAN DARI LAMAN WEB (30 Hari Terakhir) ###\n";
$report_text .= "- Jumlah Jualan: " . money($total_sales) . "\n";
$report_text .= "- Jumlah Pesanan Berbayar: " . $total_orders . "\n";
$report_text .= "- Nilai Purata Pesanan (AOV): " . money($aov) . "\n";
$report_text .= "- Pakej Terlaris: " . $best_package . "\n";
$report_text .= "- Profil Pelanggan Terbanyak: " . $top_profile . "\n";
$report_text .= "- Kadar Kejayaan Order Bump: " . $bump_rate . "%\n\n";

if (!empty($utm_breakdown)) {
    $report_text .= "### PECAHAN JUALAN MENGIKUT SUMBER TRAFIK (UTM) ###\n";
    foreach ($utm_breakdown as $row) {
        $report_text .= "- " . ucfirst(e($row['utm_source'])) . ": " . money($row['total_sales']) . " (" . $row['total_orders'] . " pesanan)\n";
    }
    $report_text .= "\n";
}

$report_text .= "### KEPUTUSAN UJIAN A/B HEADLINE (Keseluruhan) ###\n";
$report_text .= "- Headline A CVR: " . $cvr_a . "% (Teks: \"" . e($headline_a_text) . "\")\n";
$report_text .= "- Headline B CVR: " . $cvr_b . "% (Teks: \"" . e($headline_b_text) . "\")\n";
$report_text .= "- Pemenang: Headline " . $winner . "\n\n";

$report_text .= "### DATA IKLAN (SILA SALIN & ISI SECARA MANUAL DARI ADS MANAGER) ###\n";
$report_text .= "- Jumlah Kos Iklan Facebook: [Isi di sini]\n";
$report_text .= "- Jumlah Kos Iklan TikTok: [Isi di sini]\n\n";
$report_text .= "---\n";
$report_text .= "Berdasarkan semua data di atas, berikan 3 cadangan penambahbaikan yang spesifik dan boleh dilaksanakan untuk meningkatkan jualan dan ROI perniagaan ini.";

?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../public/assets/css/style.css">
    <title>Analisis AI</title>
    <style>
        .admin-wrapper { display: flex; align-items: flex-start; gap: 24px; }
        .admin-sidebar { width: 220px; flex-shrink: 0; }
        .admin-content { flex-grow: 1; }
        .report-area { width: 100%; height: 500px; font-family: monospace; font-size: 14px; line-height: 1.6; padding: 15px; border: 1px solid #d1d5db; border-radius: 8px; }
        .copy-button { display: block; width: 100%; margin-top: 15px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 12px; text-align: left; border: 1px solid #e5e7eb; }
        th { background-color: #f8fafc; }
        td.winner { background-color: #dcfce7; font-weight: bold; }
        .headline-text { font-style: italic; color: #475569; display: block; margin-top: 5px; font-size: 14px; }
    </style>
</head>
<body>
<div class="container">
    <div class="admin-wrapper">
        <aside class="admin-sidebar"><?php require_once '_menu.php'; ?></aside>
        <main class="admin-content">
            <h1>Analisis AI & Cadangan</h1>
            
            <div class="card">
                <h2>Laporan Ujian A/B Headline</h2>
                <table>
                    <tr><th>Metrik</th><th>Headline A</th><th>Headline B</th></tr>
                    <tr>
                        <td><strong>Teks Headline</strong></td>
                        <td><span class="headline-text">"<?= e($headline_a_text) ?>"</span></td>
                        <td><span class="headline-text">"<?= e($headline_b_text) ?>"</span></td>
                    </tr>
                    <tr><td>Jumlah Pelawat</td><td><?= number_format($visits_a) ?></td><td><?= number_format($visits_b) ?></td></tr>
                    <tr><td>Jumlah Jualan</td><td><?= number_format($sales_a) ?></td><td><?= number_format($sales_b) ?></td></tr>
                    <tr>
                        <td><strong>Kadar Penukaran (CVR)</strong></td>
                        <td class="<?= $winner === 'A' ? 'winner' : '' ?>"><?= $cvr_a ?>%</td>
                        <td class="<?= $winner === 'B' ? 'winner' : '' ?>"><?= $cvr_b ?>%</td>
                    </tr>
                </table>
            </div>

            <div class="card">
                <h2>Rumusan Data Sedia untuk AI</h2>
                <ol>
                    <li>(Pilihan) Isi maklumat dari Facebook/TikTok Ads Manager anda di ruangan "[Isi di sini]".</li>
                    <li>Klik butang **"Salin Teks"**.</li>
                    <li>Tampal teks tersebut ke dalam platform AI pilihan anda (ChatGPT, Gemini, dll.).</li>
                </ol>
                <textarea id="report-text" class="report-area"><?= e($report_text) ?></textarea>
                <button id="copy-btn" class="cta copy-button">Salin Teks</button>
            </div>
        </main>
    </div>
</div>
<script>
document.getElementById('copy-btn').addEventListener('click', function() {
    const textArea = document.getElementById('report-text');
    textArea.select();
    document.execCommand('copy');
    this.textContent = 'Berjaya Disalin!';
    setTimeout(() => { this.textContent = 'Salin Teks'; }, 2000);
});
</script>
</body>
</html>