<?php
/**
 * update_status.php — AJAX handler
 * -----------------------------------------------------------
 *  • Menerima   : id  (INT), status (STRING: pending|ditolak|disetujui), note (optional)
 *  • Logika     :
 *      - Simpan status (dan catatan jika ada) ke DB.
 *      - Kirim e‑mail:
 *          • disetujui  →  e‑mail + PDF terlampir
 *          • ditolak    →  e‑mail hanya berisi catatan (tanpa lampiran)
 *          • pending    →  tidak kirim e‑mail
 * -----------------------------------------------------------*/

session_start();
if (!isset($_SESSION['admin_id'])) {
  header('Location: login_admin.php');
  exit;
}

require '../db.php';               // $conn
require 'reservation_pdf.php';     // fungsi buatPDFReservasi()
require '../vendor/autoload.php';  // PHPMailer

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

// ---------- Input & sanitasi ----------
$id     = filter_input(INPUT_POST, 'id',     FILTER_VALIDATE_INT);
$status = filter_input(INPUT_POST, 'status', FILTER_SANITIZE_STRING);
$note   = trim($_POST['note'] ?? '');        // catatan opsional

$allowed = ['pending','ditolak','disetujui'];
if (!$id || !in_array($status, $allowed)) {
  echo 'invalid';
  exit;
}

// ---------- Update database ----------
if ($status === 'ditolak') {
  // pastikan kolom catatan ada (TEXT)
  $stmt = $conn->prepare("UPDATE reservations SET status=?, catatan=? WHERE id=?");
  $stmt->bind_param('ssi', $status, $note, $id);
} else {
  $stmt = $conn->prepare("UPDATE reservations SET status=? WHERE id=?");
  $stmt->bind_param('si', $status, $id);
}

if (!$stmt->execute()) {
  echo 'db_error';
  exit;
}

// ---------- Ambil data reservasi ----------
$res = $conn->prepare("SELECT * FROM reservations WHERE id=?");
$res->bind_param('i', $id);
$res->execute();
$reservation = $res->get_result()->fetch_assoc();

// ---------- Siapkan PHPMailer ----------
$mail = new PHPMailer(true);
try {
  $mail->isSMTP();
  $mail->Host       = 'smtp.gmail.com';
  $mail->SMTPAuth   = true;
  $mail->Username   = 'budparreservasi@gmail.com';
  $mail->Password   = 'vtyw pgrg hlgr rqcf'; // ganti dengan App‑Password
  $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
  $mail->Port       = 587;

  $mail->setFrom('budparreservasi@gmail.com', 'Budpar Reservasi');
  $mail->addAddress($reservation['surat']);
  $mail->isHTML(true);

  // ---------- Konten E‑mail ----------
  if ($status === 'disetujui') {
      $mail->Subject = 'Reservasi Anda DISETUJUI — #'.$reservation['kode_booking'];
      $mail->Body    = '<p>Halo '.htmlspecialchars($reservation['nama']).',</p>'
                     . '<p>Reservasi Anda telah <b>DISETUJUI</b>. Detail terlampir dalam PDF berikut.</p>';
      // lampiran PDF
      $pdfString = buatPDFReservasi($reservation, $status);
      $mail->addStringAttachment($pdfString,
        'Surat_Reservasi_'.$reservation['kode_booking'].'.pdf','base64','application/pdf');
  }
  elseif ($status === 'ditolak') {
      $mail->Subject = 'Reservasi Anda DITOLAK - #'.$reservation['kode_booking'];
      $mail->Body    = '<p>Halo '.htmlspecialchars($reservation['nama']).',</p>'
                     . '<p>Mohon maaf, reservasi Anda <b>DITOLAK</b> dengan catatan berikut:</p>'
                     . '<blockquote style="border-left:4px solid #f0ad4e;padding-left:10px;color:#444">'
                     . nl2br(htmlspecialchars($note ?: '-')) . '</blockquote>'
                     . '<p>Silakan ajukan ulang atau hubungi kami untuk informasi lebih lanjut.</p>';
      // ‑‑ tidak ada attachment
  } else { // pending
      echo 'OK';
      exit; // tidak kirim email
  }

  $mail->send();
} catch (Exception $e) {
  // catat ke log jika perlu, tapi tetap balas OK ke client
}

echo 'OK';