<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();
if (empty($_POST) && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0) {
    jsonResponse(false, 'Ralat: Saiz fail melebihi had maksimum pelayan. Sila muat naik fail atau gambar bersaiz lebih kecil (bawah 30MB).');
}
if(!verifyCsrfToken($_POST['csrf_token']??''))jsonResponse(false,'CSRF Error');
$tajuk=sanitize($_POST['tajuk']??'');
if(!$tajuk)jsonResponse(false,'Tajuk diperlukan.');
// Dapatkan unit_id dari user atau form
$unit_id=null;
if(isAdmin()&&isset($_POST['unit_id'])&&$_POST['unit_id']!=''){
  $unit_id=intval($_POST['unit_id']);
}elseif(!isAdmin()){
  // Pegawai biasa - guna unit mereka sendiri
  $uq=$pdo->prepare("SELECT unit_id FROM pegawai WHERE id=(SELECT pegawai_id FROM users WHERE id=?)");
  $uq->execute([currentUserId()]);$uq=$uq->fetch();
  $unit_id=$uq['unit_id']??null;
}
$pegawai_id = $_SESSION['pegawai_id'] ?? null;
$id = intval($_POST['id'] ?? 0);
$gambar = '';

if ($id > 0) {
    // Mode Update
    $stmt = $pdo->prepare("SELECT * FROM success_stories WHERE id = ?");
    $stmt->execute([$id]);
    $old = $stmt->fetch();
    if (!$old) jsonResponse(false, 'Rekod tidak dijumpai.');

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

    $gambar = $old['gambar'];
    if (!empty($_FILES['gambar']['name'])) {
        $r = uploadImage($_FILES['gambar'], 'gallery');
        if ($r['success']) {
            if ($gambar) deleteFile('gallery/' . $gambar);
            $gambar = $r['filename'];
        } else {
            jsonResponse(false, $r['message']);
        }
    }

    $stmt = $pdo->prepare("UPDATE success_stories SET unit_id=?, tajuk=?, kandungan=?, gambar=?, tarikh=? WHERE id=?");
    $stmt->execute([$unit_id, $tajuk, sanitize($_POST['kandungan']??''), $gambar, ($_POST['tarikh']??null)?:null, $id]);
    logActivity('Kemaskini', 'success_stories', $id, 'Kemaskini success story: ' . $tajuk);
    jsonResponse(true, 'Success story berjaya dikemaskini!');
} else {
    // Mode Tambah
    if (!empty($_FILES['gambar']['name'])) {
        $r = uploadImage($_FILES['gambar'], 'gallery');
        if ($r['success']) {
            $gambar = $r['filename'];
        } else {
            jsonResponse(false, $r['message']);
        }
    }
    $stmt = $pdo->prepare("INSERT INTO success_stories (unit_id, tajuk, kandungan, gambar, tarikh, pegawai_id, user_id) VALUES (?,?,?,?,?,?,?)");
    $stmt->execute([$unit_id, $tajuk, sanitize($_POST['kandungan']??''), $gambar, ($_POST['tarikh']??null)?:null, $pegawai_id, currentUserId()]);
    logActivity('Tambah', 'success_stories', $pdo->lastInsertId(), 'Tambah success story: ' . $tajuk);
    jsonResponse(true, 'Success story ditambah!');
}
