<?php 
session_start();

// 1. IMPORT PHPMailer (Wajib untuk kirim email)
require '../includes/phpmailer/Exception.php';
require '../includes/phpmailer/PHPMailer.php';
require '../includes/phpmailer/SMTP.php';

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

if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) {
    header("Location: index.php");
    exit();
}

include '../includes/config.php'; 

// --- LOGIKA UPDATE DATA ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'];
    $status_baru = trim($_POST['status']); 
    $catatan = trim($_POST['catatan_admin'] ?? '');
    
    $allowed_status = ['Baru', 'Diproses', 'Selesai', 'Ditolak'];
    
    if (in_array($status_baru, $allowed_status)) {
        try {
            // A. Ambil Email, Nama Pelapor & Kode Tracking dengan JOIN
            $sql_info = "SELECT l.kode_tracking, p.email, p.nama_lengkap 
                         FROM laporan l 
                         JOIN pelapor p ON l.pelapor_id = p.id 
                         WHERE l.id = ?";
            $stmt_info = $pdo->prepare($sql_info);
            $stmt_info->execute([$id]);
            $data_pelapor = $stmt_info->fetch();

            // B. Update Database
            $sql = "UPDATE laporan SET status = ?, catatan_admin = ?, updated_at = NOW() WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $success = $stmt->execute([$status_baru, $catatan, $id]);

            if ($success) {
                // C. KIRIM EMAIL NOTIFIKASI (Jika bukan status 'Baru')
                if ($status_baru !== 'Baru' && $data_pelapor && !empty($data_pelapor['email'])) {
                    $mail = new PHPMailer(true);
                    try {
                        $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)
                        );

                        $mail->setFrom(SMTP_USER, 'Sistem TANGKIS BPS');
                        $mail->addAddress($data_pelapor['email'], $data_pelapor['nama_lengkap']); 

                        // Tentukan Tema Warna Email & Teks Label Berdasarkan Status (Lebih rapi dengan Switch)
                        switch ($status_baru) {
                            case 'Diproses':
                                $warna = '#ffc107'; // Kuning
                                $label_status = 'DALAM PROSES';
                                break;
                            case 'Selesai':
                                $warna = '#198754'; // Hijau
                                $label_status = 'SELESAI / TERBUKTI';
                                break;
                            case 'Ditolak':
                                $warna = '#dc3545'; // Merah
                                $label_status = 'DITOLAK / TIDAK TERBUKTI';
                                break;
                            default:
                                $warna = '#212529';
                                $label_status = strtoupper($status_baru);
                                break;
                        }

                        $mail->isHTML(true);
                        $mail->CharSet = 'UTF-8';
                        $mail->Subject = "[UPDATE PROGRES] Laporan #" . $data_pelapor['kode_tracking'];
                        $mail->Body    = "
                            <div style='font-family: Arial, sans-serif; padding: 20px; border: 1px solid #eee; max-width: 600px; margin: 0 auto; color: #333;'>
                                <h2 style='color: $warna; border-bottom: 2px solid $warna; padding-bottom: 10px;'>Pemberitahuan Sistem TANGKIS</h2>
                                <p>Halo <b>" . htmlspecialchars($data_pelapor['nama_lengkap']) . "</b>,</p>
                                <p>Laporan pengaduan Anda dengan kode tracking <b>#" . $data_pelapor['kode_tracking'] . "</b> telah diperbarui oleh Admin BPS Lampung Timur menjadi:</p>
                                
                                <div style='background: $warna; color: white; padding: 12px; text-align: center; border-radius: 6px; font-weight: bold; font-size: 16px; margin: 20px 0;'>
                                    " . $label_status . "
                                </div>
                                
                                <p style='margin-top:20px; background-color: #f8f9fa; padding: 15px; border-left: 4px solid $warna; border-radius: 4px;'>
                                    <b>Tanggapan / Catatan Admin:</b><br>
                                    <span style='color: #555; font-style: italic;'>\"" . htmlspecialchars($catatan ?: 'Laporan sedang ditindaklanjuti oleh tim internal.') . "\"</span>
                                </p>
                                <br>
                                <p style='font-size: 13px; color: #777;'>Anda dapat memantau detail riwayat perkembangan penanganan ini melalui menu <b>Riwayat Laporan</b> pada aplikasi utama kami.</p>
                                <hr style='border: 0; border-top: 1px solid #eee; margin: 20px 0;'>
                                <p>Terima kasih atas laporan Anda,<br><b>Tim TANGKIS BPS Lampung Timur</b></p>
                            </div>";

                        $mail->send();
                    } catch (Exception $e) {
                        error_log("Gagal kirim email: {$mail->ErrorInfo}");
                    }
                }

                header("Location: dashboard.php?msg=success");
                exit();
            }
        } catch (PDOException $e) {
            die("Gagal update: " . $e->getMessage());
        }
    } else {
        die("Status tidak valid.");
    }
}

// --- AMBIL DATA UNTUK FORM ---
$id = $_GET['id'] ?? $_POST['id'] ?? null;
if (!$id) { header("Location: dashboard.php"); exit(); }

try {
    $stmt = $pdo->prepare("SELECT kode_tracking, status, catatan_admin FROM laporan WHERE id = ?");
    $stmt->execute([$id]);
    $data = $stmt->fetch();
    if (!$data) { die("Data tidak ditemukan."); }
} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}

include '../includes/header.php';
?>

<style>
    body { background-color: #f8f9fa; }
    .card-update { border: none; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.08); }
    .status-container { display: flex; flex-direction: column; gap: 10px; }
    
    .status-box {
        position: relative; 
        padding: 15px 20px; 
        border: 2px solid #edf2f7;
        border-radius: 12px; 
        cursor: pointer; 
        transition: all 0.2s ease;
        display: flex; 
        align-items: center; 
        background: white;
    }

    /* Memperbaiki Selector CSS agar deteksi :checked berfungsi pada parent label */
    .status-box:has(input[value="Baru"]:checked) { border-color: #dc3545; background: #fff5f5; }
    .status-box:has(input[value="Diproses"]:checked) { border-color: #ffc107; background: #fffbeb; }
    .status-box:has(input[value="Selesai"]:checked) { border-color: #198754; background: #f0fff4; }
    .status-box:has(input[value="Ditolak"]:checked) { border-color: #212529; background: #f8f9fa; }

    .status-box input[type="radio"] { position: absolute; opacity: 0; }
    
    .indicator { 
        width: 20px; height: 20px; 
        border: 2px solid #cbd5e0; 
        border-radius: 50%; 
        margin-right: 15px; 
        display: inline-block;
        position: relative;
    }

    /* Indikator titik di tengah saat dipilih */
    input:checked + .indicator::after {
        content: "";
        width: 10px; height: 10px;
        background: white;
        border-radius: 50%;
        position: absolute;
        top: 50%; left: 50%;
        transform: translate(-50%, -50%);
    }

    input[value="Baru"]:checked + .indicator { background: #dc3545; border-color: #dc3545; }
    input[value="Diproses"]:checked + .indicator { background: #ffc107; border-color: #ffc107; }
    input[value="Selesai"]:checked + .indicator { background: #198754; border-color: #198754; }
    input[value="Ditolak"]:checked + .indicator { background: #212529; border-color: #212529; }
</style>

<div class="container my-5">
    <div class="row justify-content-center">
        <div class="col-lg-5 col-md-8">
            <div class="card card-update">
                <div class="card-body p-4 p-md-5">
                    <div class="text-center mb-4">
                        <h4 class="fw-bold">Update Progres</h4>
                        <p class="text-muted">ID: <span class="fw-bold text-dark">#<?= htmlspecialchars($data['kode_tracking']) ?></span></p>
                    </div>

                    <form action="update_status.php" method="POST">
                        <input type="hidden" name="id" value="<?= htmlspecialchars($id) ?>">

                        <div class="mb-4">
                            <label class="form-label small fw-bold text-muted mb-3 text-uppercase">Pilih Status Terbaru</label>
                            <div class="status-container">
                                <?php 
                                $options = [
                                    'Baru' => ['color' => 'danger', 'icon' => 'star-fill', 'label' => 'Baru (Antrian)'],
                                    'Diproses' => ['color' => 'warning', 'icon' => 'gear-fill', 'label' => 'Dalam Proses'],
                                    'Selesai' => ['color' => 'success', 'icon' => 'check-circle-fill', 'label' => 'Selesai / Terbukti'],
                                    'Ditolak' => ['color' => 'dark', 'icon' => 'x-circle-fill', 'label' => 'Ditolak / Tidak Terbukti']
                                ];
                                foreach ($options as $val => $opt): 
                                ?>
                                <label class="status-box">
                                    <input type="radio" name="status" value="<?= $val ?>" <?= ($data['status'] == $val) ? 'checked' : '' ?> required>
                                    <span class="indicator"></span>
                                    <span class="fw-semibold">
                                        <i class="bi bi-<?= $opt['icon'] ?> me-2 text-<?= $opt['color'] ?>"></i> 
                                        <?= $opt['label'] ?>
                                    </span>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label small fw-bold text-muted text-uppercase">Tanggapan Resmi Admin</label>
                            <textarea name="catatan_admin" class="form-control" rows="4" placeholder="Berikan alasan atau instruksi lanjutan untuk pelapor..." style="border-radius: 12px;"><?= htmlspecialchars($data['catatan_admin'] ?? '') ?></textarea>
                        </div>

                        <button type="submit" class="btn btn-primary w-100 btn-lg rounded-pill fw-bold shadow-sm">Simpan Perubahan</button>
                        <div class="text-center mt-3">
                            <a href="dashboard.php" class="text-muted text-decoration-none small"><i class="bi bi-arrow-left"></i> Kembali ke Dashboard</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>