<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as WriterXlsx;
use setasign\Fpdi\Fpdi;

$data = [];
$stats = [];
$headers = [];
$error_message = '';
$file_uploaded = false;

// --- Bagian Logika Pengunggahan dan Analisis ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file_upload'])) {
    $file_uploaded = true;

    // Periksa kode kesalahan unggahan PHP
    switch ($_FILES['file_upload']['error']) {
        case UPLOAD_ERR_OK:
            // Tidak ada kesalahan, lanjutkan
            break;
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            $error_message = 'Ukuran file terlalu besar. Harap unggah file yang lebih kecil.';
            break;
        case UPLOAD_ERR_NO_FILE:
            $error_message = 'Tidak ada file yang diunggah. Silakan pilih file.';
            break;
        default:
            $error_message = 'Terjadi kesalahan tidak dikenal saat mengunggah file.';
            break;
    }

    if (empty($error_message)) {
        $file_path = $_FILES['file_upload']['tmp_name'];
        $file_ext = strtolower(pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION));

        if (!in_array($file_ext, ['csv', 'xlsx'])) {
            $error_message = 'Hanya file CSV atau XLSX yang diperbolehkan.';
        } else {
            try {
                if ($file_ext === 'xlsx') {
                    $reader = new Xlsx();
                } else {
                    $reader = new Csv();
                }
                
                $spreadsheet = $reader->load($file_path);
                $sheet = $spreadsheet->getActiveSheet();
                $data = $sheet->toArray(null, true, true, true);
                
                if (!empty($data)) {
                    $headers = array_shift($data);

                    foreach ($headers as $key => $header_name) {
                        $column_data = array_column($data, $key);
                        $numeric_data = array_filter($column_data, 'is_numeric');

                        if (!empty($numeric_data)) {
                            $stats[$header_name] = [
                                'type' => 'numeric',
                                'total' => array_sum($numeric_data),
                                'average' => count($numeric_data) > 0 ? array_sum($numeric_data) / count($numeric_data) : 0,
                                'min' => min($numeric_data),
                                'max' => max($numeric_data)
                            ];
                        } else {
                            $category_counts = array_count_values(array_filter($column_data));
                            $stats[$header_name] = [
                                'type' => 'categorical',
                                'counts' => $category_counts,
                            ];
                        }
                    }

                    // Simpan data dan statistik ke sesi
                    $_SESSION['data'] = $data;
                    $_SESSION['headers'] = $headers;
                    $_SESSION['stats'] = $stats;
                    $_SESSION['file_uploaded'] = true;
                    $_SESSION['chart_images'] = []; // Reset chart images

                } else {
                    $error_message = 'File kosong atau tidak berisi data yang valid.';
                }
            } catch (\Exception $e) {
                $error_message = 'Gagal membaca file: ' . $e->getMessage();
            }
        }
    }
}

// --- Logika Penyimpanan Gambar dari AJAX ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_charts']) && isset($_POST['charts_data'])) {
    $_SESSION['chart_images'] = json_decode($_POST['charts_data'], true);
    echo json_encode(['status' => 'success']);
    exit;
}

// --- Bagian Logika Ekspor Data & PDF (menggunakan GET) ---
if (isset($_GET['export'])) {
    if ($_GET['export'] === 'pdf') {
        if (!isset($_SESSION['chart_images']) || empty($_SESSION['chart_images'])) {
            die('Tidak ada gambar grafik untuk diekspor. Silakan coba unggah file lagi.');
        }

        $pdf = new Fpdi('P', 'mm', 'A4');
        $pdf->SetFont('Arial', '', 12);

        foreach ($_SESSION['chart_images'] as $header => $base64_image) {
            $image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64_image));
            $temp_file = sys_get_temp_dir() . '/' . uniqid('chart_') . '.png';
            
            // Pastikan direktori sementara bisa ditulis
            if (!is_writable(sys_get_temp_dir())) {
                die("Direktori sementara tidak dapat ditulis: " . sys_get_temp_dir());
            }

            file_put_contents($temp_file, $image_data);

            $pdf->AddPage();
            $pdf->SetY(10);
            $pdf->SetX(10);
            $pdf->Cell(0, 10, 'Analisis Kolom: ' . $header, 0, 1, 'C');
            $pdf->Image($temp_file, 15, 25, 180);
            unlink($temp_file); // Hapus file sementara
        }

        $pdf->Output('D', 'analisis_data.pdf');
        exit;
    } 
    
    // Logika Ekspor Excel
    else {
        if (!isset($_SESSION['data']) || !isset($_SESSION['headers'])) {
            die('Tidak ada data untuk diekspor.');
        }

        $data = $_SESSION['data'];
        $headers = $_SESSION['headers'];
        $columnToExport = $_GET['export'];

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $exportData = [];

        if ($columnToExport === 'all') {
            $exportData[] = $headers;
            foreach ($data as $row) {
                $exportData[] = $row;
            }
            $filename = "semua_data.xlsx";
        } else {
            $columnIndex = array_search($columnToExport, $headers);
            if ($columnIndex !== false) {
                $exportData[] = [$columnToExport];
                foreach ($data as $row) {
                    $exportData[] = [$row[$columnIndex]];
                }
                $filename = "data_kolom_" . str_replace(' ', '_', $columnToExport) . ".xlsx";
            } else {
                die('Kolom tidak ditemukan.');
            }
        }
        
        $sheet->fromArray($exportData, NULL, 'A1');

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = new WriterXlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }
}

// Ambil data dari sesi jika sudah diunggah sebelumnya
if (isset($_SESSION['file_uploaded']) && $_SESSION['file_uploaded']) {
    $file_uploaded = true;
    $stats = $_SESSION['stats'];
    $headers = $_SESSION['headers'];
    $data = $_SESSION['data'];
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alat Analisis Data Otomatis</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --primary-color: #4A90E2;
            --secondary-color: #50E3C2;
            --accent-color: #F5A623;
            --bg-color: #f0f2f5;
            --card-bg-color: #ffffff;
            --border-color: #e3e8ee;
            --text-color: #333d47;
            --text-light: #7a828d;
            --shadow-light: 0 4px 15px rgba(0, 0, 0, 0.08);
            --shadow-heavy: 0 8px 25px rgba(0, 0, 0, 0.1);
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--bg-color);
            margin: 0;
            color: var(--text-color);
            line-height: 1.6;
        }

        .container {
            max-width: 1100px;
            margin: 0 auto;
            padding: 30px;
        }

        header {
            text-align: center;
            padding: 80px 20px 60px;
            margin-bottom: 40px;
            background: linear-gradient(135deg, var(--primary-color) 0%, #76b1f2 100%);
            color: white;
            border-radius: 20px;
            box-shadow: var(--shadow-heavy);
        }
        
        header h1 {
            font-size: 3.2em;
            font-weight: 700;
            margin: 0;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        }

        header p {
            font-size: 1.2em;
            margin-top: 15px;
            font-weight: 300;
        }

        .upload-section {
            background-color: var(--card-bg-color);
            padding: 50px;
            border-radius: 15px;
            box-shadow: var(--shadow-light);
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 30px;
        }
        
        form {
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .file-input-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
            width: 100%;
            max-width: 500px;
            border: 3px dashed var(--border-color);
            border-radius: 12px;
            padding: 40px 20px;
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .file-input-wrapper:hover {
            border-color: var(--primary-color);
            background-color: #f8f9fa;
        }

        .file-label {
            font-weight: 600;
            color: var(--primary-color);
            cursor: pointer;
            font-size: 1.2em;
        }

        .file-label p {
            margin: 0;
        }
        
        input[type="file"] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
            width: 100%;
            height: 100%;
        }

        .file-name {
            display: block;
            margin-top: 15px;
            color: var(--text-light);
            font-style: italic;
            font-size: 0.9em;
            word-wrap: break-word;
        }

        .button-primary {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 15px 40px;
            font-size: 1.1em;
            font-weight: 600;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 20px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .button-primary:hover {
            background-color: #3b74b8;
            transform: translateY(-3px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        .results-section {
            margin-top: 40px;
            opacity: 0;
            animation: fadeIn 0.8s forwards;
            animation-delay: 0.5s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .summary-box {
            background-color: var(--card-bg-color);
            padding: 30px;
            border-radius: 15px;
            box-shadow: var(--shadow-light);
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
            gap: 30px;
            margin-bottom: 40px;
            text-align: center;
        }
        
        .summary-item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .summary-item p {
            margin: 0;
            color: var(--text-light);
            font-weight: 400;
            font-size: 0.9em;
        }

        .summary-item span {
            font-weight: 700;
            color: var(--primary-color);
            font-size: 2em;
            line-height: 1.2;
        }

        .charts-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 30px;
        }

        .chart-card {
            background-color: var(--card-bg-color);
            padding: 30px;
            border-radius: 15px;
            box-shadow: var(--shadow-light);
            text-align: center;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        
        .chart-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-heavy);
        }
        
        .chart-card h3 {
            margin-top: 0;
            color: var(--primary-color);
            font-size: 1.6em;
            font-weight: 600;
        }

        .stats-list {
            text-align: left;
            margin: 10px 0 20px;
            list-style: none;
            padding: 0;
        }

        .stats-list li {
            margin: 8px 0;
            color: var(--text-color);
            font-weight: 400;
        }
        
        .stats-list span {
            font-weight: 600;
            color: var(--primary-color);
        }

        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            font-weight: 600;
            text-align: center;
            border-left: 5px solid;
        }

        .alert-danger {
            color: #721c24;
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }

        .button-small {
            background-color: var(--secondary-color);
            color: white;
            border: none;
            padding: 10px 25px;
            font-size: 0.9em;
            font-weight: 600;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .button-small.export {
            background-color: var(--accent-color);
        }

        .button-small:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .button-small.export:hover {
            background-color: #d18d1a;
        }
        
        .chart-actions {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 10px;
        }

        .chart-actions-global {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        
        footer {
            text-align: center;
            padding: 40px 0;
            margin-top: 40px;
            color: var(--text-light);
            font-size: 0.9em;
        }

        @media (max-width: 768px) {
            header {
                padding: 60px 20px 40px;
            }

            header h1 {
                font-size: 2.5em;
            }

            .summary-box {
                flex-direction: column;
                gap: 20px;
            }

            .charts-container {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>Data Analyzer</h1>
            <p>Unggah file CSV atau XLSX Anda. Dapatkan statistik dan visualisasi otomatis!</p>
        </header>

        <main>
            <section class="upload-section">
                <form action="" method="post" enctype="multipart/form-data">
                    <div class="file-input-wrapper">
                        <label for="file_upload" class="file-label">
                            <p>Drag & Drop atau Klik untuk Unggah</p>
                            <input type="file" name="file_upload" id="file_upload" accept=".csv,.xlsx" required>
                        </label>
                        <span class="file-name">Belum ada file yang dipilih</span>
                    </div>
                    <button type="submit" class="button-primary">Analisis Data</button>
                </form>
            </section>

            <?php if ($file_uploaded): ?>
                <section class="results-section">
                    <?php if (!empty($error_message)): ?>
                        <div class="alert alert-danger"><?= htmlspecialchars($error_message); ?></div>
                    <?php else: ?>
                        <div class="summary-box">
                            <div class="summary-item">
                                <p>Jumlah Baris</p>
                                <span><?= count($data); ?></span>
                            </div>
                            <div class="summary-item">
                                <p>Jumlah Kolom</p>
                                <span><?= count($headers); ?></span>
                            </div>
                        </div>
                        
                        <div class="chart-actions-global">
                            <button id="download-all-charts" class="button-small">Unduh Semua Gambar</button>
                            <button id="export-all-data" class="button-small export">Ekspor Semua Data</button>
                            <button id="export-all-pdf" class="button-small">Ekspor Ke PDF</button>
                        </div>

                        <div class="charts-container">
                            <?php foreach ($stats as $header => $stat): ?>
                                <div class="chart-card">
                                    <h3><?= htmlspecialchars($header); ?></h3>
                                    <?php if ($stat['type'] === 'numeric'): ?>
                                        <ul class="stats-list">
                                            <li>Total: <span><?= number_format($stat['total']); ?></span></li>
                                            <li>Rata-rata: <span><?= number_format($stat['average'], 2); ?></span></li>
                                            <li>Min: <span><?= number_format($stat['min']); ?></span></li>
                                            <li>Max: <span><?= number_format($stat['max']); ?></span></li>
                                        </ul>
                                        <canvas id="chart-<?= str_replace(' ', '-', $header); ?>"></canvas>
                                    <?php elseif ($stat['type'] === 'categorical'): ?>
                                        <ul class="stats-list">
                                            <li>Kategori Unik: <span><?= count($stat['counts']); ?></span></li>
                                        </ul>
                                        <canvas id="chart-<?= str_replace(' ', '-', $header); ?>"></canvas>
                                    <?php endif; ?>
                                    <div class="chart-actions">
                                        <button class="button-small download-btn" data-chart-id="chart-<?= str_replace(' ', '-', $header); ?>">Unduh Gambar</button>
                                        <button class="button-small export-btn export" data-header-name="<?= htmlspecialchars($header); ?>">Ekspor Data</button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </section>
            <?php endif; ?>
        </main>
        
        <footer>
            <p>Dibuat dengan ❤️ untuk komunitas. Anda dapat menemukan kode ini di [GitHub/Link Anda].</p>
        </footer>
    </div>

    <script>
        document.getElementById('file_upload').addEventListener('change', function(e) {
            const fileName = e.target.files[0] ? e.target.files[0].name : 'Belum ada file yang dipilih';
            document.querySelector('.file-name').textContent = fileName;
        });

        // Loop untuk membuat semua chart
        <?php foreach ($stats as $header => $stat): ?>
            <?php 
            $chart_id = str_replace(' ', '-', $header);
            $chart_labels = [];
            $chart_data = [];
            $chart_type = '';
            $chart_bg_colors = [];

            if ($stat['type'] === 'numeric') {
                $chart_type = 'bar';
                $chart_labels = ['Min', 'Rata-rata', 'Max'];
                $chart_data = [$stat['min'], $stat['average'], $stat['max']];
                $chart_bg_colors = ['#28a745', '#4A90E2', '#dc3545'];
            } elseif ($stat['type'] === 'categorical') {
                $chart_type = 'pie';
                $chart_labels = array_keys($stat['counts']);
                $chart_data = array_values($stat['counts']);
                $chart_bg_colors = ['#4A90E2', '#50E3C2', '#F5A623', '#dc3545', '#6c757d', '#17a2b8'];
            }
            ?>
            const ctx_<?= $chart_id; ?> = document.getElementById('chart-<?= $chart_id; ?>');
            new Chart(ctx_<?= $chart_id; ?>, {
                type: '<?= $chart_type; ?>',
                data: {
                    labels: <?= json_encode($chart_labels); ?>,
                    datasets: [{
                        label: 'Nilai',
                        data: <?= json_encode($chart_data); ?>,
                        backgroundColor: <?= json_encode($chart_bg_colors); ?>
                    }]
                },
                options: { 
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'top',
                            display: '<?= $stat['type'] === 'categorical' ? 'true' : 'false' ?>'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            display: '<?= $stat['type'] === 'numeric' ? 'true' : 'false' ?>'
                        }
                    }
                }
            });
        <?php endforeach; ?>

        // Logika untuk mengunduh gambar per chart
        document.querySelectorAll('.download-btn').forEach(button => {
            button.addEventListener('click', function() {
                const chartId = this.getAttribute('data-chart-id');
                const canvas = document.getElementById(chartId);
                const image = canvas.toDataURL('image/png');
                const link = document.createElement('a');
                link.href = image;
                link.download = chartId + '.png';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            });
        });

        // Logika untuk mengunduh semua gambar
        document.getElementById('download-all-charts').addEventListener('click', function() {
            const chartsContainer = document.querySelector('.charts-container');
            const chartCards = chartsContainer.querySelectorAll('.chart-card');
            
            chartCards.forEach(card => {
                const canvas = card.querySelector('canvas');
                if (canvas) {
                    const chartId = canvas.id;
                    const image = canvas.toDataURL('image/png');
                    const link = document.createElement('a');
                    link.href = image;
                    link.download = chartId + '.png';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }
            });
        });

        // Logika untuk ekspor data per kolom
        document.querySelectorAll('.export-btn').forEach(button => {
            button.addEventListener('click', function() {
                const headerName = this.getAttribute('data-header-name');
                window.location.href = `?export=${encodeURIComponent(headerName)}`;
            });
        });

        // Logika untuk ekspor semua data
        document.getElementById('export-all-data').addEventListener('click', function() {
            window.location.href = `?export=all`;
        });
        
        // Logika untuk ekspor semua grafik ke PDF
        document.getElementById('export-all-pdf').addEventListener('click', function() {
            const chartsData = {};
            const chartCards = document.querySelectorAll('.chart-card');
            
            chartCards.forEach(card => {
                const canvas = card.querySelector('canvas');
                if (canvas) {
                    const headerName = card.querySelector('h3').textContent;
                    chartsData[headerName] = canvas.toDataURL('image/png');
                }
            });

            // Kirim data ke server untuk disimpan di sesi
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    // Setelah data gambar disimpan di sesi, picu unduhan PDF
                    window.location.href = '?export=pdf';
                }
            };
            xhr.send('save_charts=true&charts_data=' + encodeURIComponent(JSON.stringify(chartsData)));
        });
    </script>
</body>
</html>