<?php 
session_start();

// 1. IMPORT PHPMailer di paling atas
require '../includes/phpmailer/Exception.php';
require '../includes/phpmailer/PHPMailer.php';
require '../includes/phpmailer/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Cek apakah pelapor sudah login
if (!isset($_SESSION['pelapor_id'])) {
    header("Location: login_pelapor.php");
    exit;
}

// Perbaikan Path Config
if (file_exists('../includes/config.php')) {
    include '../includes/config.php';
} else {
    die("Error: File config.php tidak ditemukan.");
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: lapor.php");
    exit;
}

try {
    // Ambil data dari form
    $pelapor_id = $_SESSION['pelapor_id']; 
    
    // Logika Jenis Pelanggaran
    $jenis = $_POST['apa'] ?? '';
    if ($jenis === 'Lainnya' && !empty($_POST['apa_lainnya'])) {
        $jenis = $_POST['apa_lainnya'];
    }

    $lokasi     = $_POST['dimana'] ?? '';
    $tanggal    = $_POST['kapan'] ?? '';
    $terlapor   = $_POST['siapa'] ?? '';
    $deskripsi  = $_POST['bagaimana'] ?? '';

    // Generate Kode Tracking unik
    $kode = "Tangkis-" . date('Y') . "-" . strtoupper(substr(md5(uniqid()), 0, 6));

    // --- PROSES UPLOAD BUKTI ---
    $nama_file_bukti = NULL;
    if (!empty($_FILES['bukti']['name'])) {
        $target_dir = "../assets/uploads/"; 
        if (!file_exists($target_dir)) { mkdir($target_dir, 0777, true); }
        
        $file_info = $_FILES['bukti'];
        $ext = strtolower(pathinfo($file_info['name'], PATHINFO_EXTENSION));
        $nama_file_bukti = "bukti_" . time() . "_" . $pelapor_id . "." . $ext;
        
        $allowed = ['jpg', 'jpeg', 'png', 'pdf', 'mp4', 'mov', 'doc', 'docx'];
        if (!in_array($ext, $allowed)) {
            die("Gagal: Format file tidak didukung.");
        }

        if ($file_info['size'] > 2097152) {
            die("Gagal: Ukuran file terlalu besar. Maksimal adalah 2MB.");
        }
        
        move_uploaded_file($file_info['tmp_name'], $target_dir . $nama_file_bukti);
    }

    // --- 2. SIMPAN KE DATABASE ---
    $sql = "INSERT INTO laporan (pelapor_id, kode_tracking, jenis_dugaan, lokasi, tanggal_kejadian, terlapor, deskripsi, bukti, status) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Baru')";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$pelapor_id, $kode, $jenis, $lokasi, $tanggal, $terlapor, $deskripsi, $nama_file_bukti]);
   
    // Ambil data pelapor
    $stmtPelapor = $pdo->prepare("SELECT nama_lengkap, email FROM pelapor WHERE id = ?");
    $stmtPelapor->execute([$pelapor_id]);
    $dataPelapor = $stmtPelapor->fetch();

    $namaPelapor = $dataPelapor['nama_lengkap'] ?? 'Pelapor';
    $emailPelapor = $dataPelapor['email'] ?? '';

    // --- 3. KIRIM NOTIFIKASI EMAIL KE BPS ---
    $mail = new PHPMailer(true);
    try {
        // Pengaturan SMTP (Diambil dari config.php)
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST; 
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER; 
        $mail->Password   = SMTP_PASS; 
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = SMTP_PORT;

        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        // Pengirim & Penerima
        $mail->setFrom(SMTP_USER, 'Sistem TANGKIS BPS');
        $mail->addAddress(ADMIN_EMAIL); // Mengirim ke email admin BPS

        // Konten Email Admin
        $mail->isHTML(true);
        $mail->Subject = "[NOTIFIKASI TANGKIS] Laporan Pelanggaran Baru - $kode";
        $mail->Body    = "
            <div style='font-family: Arial, sans-serif; color: #333;'>
                <h2 style='color: #0d6efd;'>Halo Admin BPS Lampung Timur,</h2>
                <p>Telah masuk laporan pengaduan baru melalui sistem <b>TANGKIS</b>.</p>
                <hr>
                <p><b>Rincian Singkat:</b></p>
                <ul>
                    <li><b>Kode Tracking:</b> $kode</li>
                    <li><b>Jenis Dugaan:</b> $jenis</li>
                    <li><b>Terlapor:</b> $terlapor</li>
                    <li><b>Lokasi:</b> $lokasi</li>
                </ul>
                <p>Silakan klik tombol di bawah untuk memeriksa detail laporan di Dashboard Admin:</p>
                <a href='".base_url('admin/')."' style='display: inline-block; padding: 10px 20px; background-color: #0d6efd; color: #ffffff; text-decoration: none; border-radius: 5px;'>Buka Dashboard Admin</a>
                <br><br>
                <p>Terima kasih,<br>Sistem TANGKIS Otomatis</p>
            </div>
        ";

        $mail->send();
    } catch (Exception $e) {
        error_log("Email ke Admin gagal dikirim: " . $mail->ErrorInfo);
    }

    // --- 4. KIRIM EMAIL KE PELAPOR ---
    if (!empty($emailPelapor) && filter_var($emailPelapor, FILTER_VALIDATE_EMAIL)) {
        try {
            $mailPelapor = new PHPMailer(true);

            $mailPelapor->isSMTP();
            $mailPelapor->Host = SMTP_HOST;
            $mailPelapor->SMTPAuth = true;
            $mailPelapor->Username = SMTP_USER;
            $mailPelapor->Password = SMTP_PASS;
            $mailPelapor->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mailPelapor->Port = SMTP_PORT;

            $mailPelapor->SMTPOptions = [
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                ]
            ];

            $mailPelapor->setFrom(SMTP_USER, 'Sistem TANGKIS BPS');
            $mailPelapor->addAddress($emailPelapor, $namaPelapor);

            $mailPelapor->isHTML(true);
            $mailPelapor->CharSet = 'UTF-8';
            $mailPelapor->Subject = "Laporan Anda Berhasil Diterima";
            $mailPelapor->Body = "
                <div style='font-family: Arial, sans-serif; color: #333;'>
                    <h2>Halo, $namaPelapor</h2>
                    <p>Terima kasih telah menyampaikan laporan melalui <b>Sistem TANGKIS</b>.</p>
                    <p>Laporan Anda berhasil diterima.</p>
                    <table border='1' cellpadding='8' cellspacing='0' style='border-collapse: collapse; border-color: #ccc;'>
                        <tr>
                            <td><b>Kode Tracking</b></td>
                            <td><b style='color: #0d6efd;'>$kode</b></td>
                        </tr>
                        <tr>
                            <td><b>Status</b></td>
                            <td>Baru</td>
                        </tr>
                        <tr>
                            <td><b>Jenis Dugaan</b></td>
                            <td>$jenis</td>
                        </tr>
                    </table>
                    <br>
                    <p>Silakan simpan kode tracking tersebut untuk memantau perkembangan laporan Anda di menu <b>Riwayat Laporan</b>.</p>
                    <br>
                    <p>Terima kasih.<br><b>Sistem TANGKIS BPS Lampung Timur</b></p>
                </div>
            ";

            $mailPelapor->send(); // Cukup dipanggil sekali di sini
        } catch (Exception $e) {
            error_log("Email pelapor gagal dikirim: " . $mailPelapor->ErrorInfo);
        }
    } else {
        error_log("Email pelapor kosong atau tidak valid.");
    }
    
    // Set flag sukses untuk memicu SweetAlert2
    $sukses = true;

} catch (PDOException $e) {
    die("Gagal menyimpan laporan ke database: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Terkirim - Tangkis</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body { font-family: 'Poppins', sans-serif; background: #f0f2f5; }
        .box-kode { 
            background: #e7f1ff; 
            border: 2px dashed #0d6efd; 
            padding: 20px; 
            font-size: 28px; 
            font-weight: 700; 
            color: #0d6efd; 
            border-radius: 15px;
            letter-spacing: 2px;
        }
    </style>
</head>
<body class="bg-light">

    <?php if (isset($sukses) && $sukses === true): ?>
    <script>
        Swal.fire({
            title: 'Berhasil Terkirim!',
            text: 'Laporan Anda sedang diproses oleh Tim Tangkis BPS.',
            icon: 'success',
            confirmButtonText: 'Lihat Kode Tracking',
            confirmButtonColor: '#0d6efd'
        });
    </script>
    <?php endif; ?>

    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-md-7 text-center">
                <div class="card shadow border-0 p-5" style="border-radius: 25px;">
                    <div class="mb-4">
                        <i class="bi bi-check-circle-fill text-success" style="font-size: 4rem;"></i>
                    </div>
                    <h2 class="fw-bold text-dark mb-3">Terima Kasih!</h2>
                    <p class="text-muted mb-4">Laporan Anda telah berhasil masuk ke sistem kami. Silakan catat atau simpan kode tracking di bawah ini:</p>
                    
                    <div class="box-kode mb-4">
                        <?= htmlspecialchars($kode) ?>
                    </div>

                    <div class="alert alert-warning small text-start mb-4">
                        <strong>Penting:</strong> Simpan kode ini untuk mengecek status laporan Anda di menu <b>Riwayat Laporan</b>.
                    </div>

                    <div class="d-flex gap-2 justify-content-center">
                        <a href="riwayat_laporan.php" class="btn btn-primary rounded-pill px-4 py-2 fw-bold">Lihat Riwayat Laporan</a>
                        <a href="index.php" class="btn btn-outline-secondary rounded-pill px-4 py-2">Ke Beranda</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
</body>
</html>