<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id'] ?? 0);
    $csrf = $_POST['csrf_token'] ?? '';

    if (!verifyCsrfToken($csrf)) {
        jsonResponse(false, 'Ralat keselamatan (CSRF).');
    }

    $stmt = $pdo->prepare("SELECT * FROM success_stories WHERE id = ?");
    $stmt->execute([$id]);
    $story = $stmt->fetch();

    if (!$story) {
        jsonResponse(false, 'Rekod tidak dijumpai.');
    }

    // Hak akses: Superadmin atau pemilik
    if (!isSuperAdmin() && (!empty($_SESSION['pegawai_id']) && $_SESSION['pegawai_id'] != $story['pegawai_id'])) {
        jsonResponse(false, 'Anda tiada kebenaran untuk memadam rekod ini.');
    }

    // Padam gambar jika ada
    if ($story['gambar']) {
        deleteFile('gallery/' . $story['gambar']);
    }

    $delete = $pdo->prepare("DELETE FROM success_stories WHERE id = ?");
    if ($delete->execute([$id])) {
        logActivity('padam', 'success_story', $id, 'Padam success story: ' . $story['tajuk']);
        jsonResponse(true, 'Success story berjaya dipadam.');
    } else {
        jsonResponse(false, 'Gagal memadam success story.');
    }
}
