<?php
session_start();
header('Content-Type: application/json');
require_once '../config/auth.php';
cek_role('admin_dpw');
include '../config/database.php';

$db = new Database();
$conn = $db->getConnection();

$response = ['status' => 'error', 'message' => 'Aksi tidak dikenal'];

if(isset($_POST['action']) && $_POST['action'] == 'hapus_struktur'){
    $id = $_POST['id'];
    
    $old = $conn->prepare("SELECT file_bagan FROM struktur_organisasi WHERE id =?");
    $old->execute([$id]);
    $file = $old->fetchColumn();
    if($file && file_exists('../assets/img/struktur/'.$file)){
        unlink('../assets/img/struktur/'.$file);
    }
    
    $stmt = $conn->prepare("DELETE FROM struktur_organisasi WHERE id =?");
    if($stmt->execute([$id])){
        $response = ['status' => 'sukses'];
    }
} else {
    $judul = $_POST['judul'];
    $periode = $_POST['periode'];
    $keterangan = $_POST['keterangan']?? '';
    
    if(isset($_FILES['file_bagan']) && $_FILES['file_bagan']['error'] == 0){
        $ext = strtolower(pathinfo($_FILES['file_bagan']['name'], PATHINFO_EXTENSION));
        if(in_array($ext, ['jpg','jpeg','png','pdf'])){
            if(!is_dir('../assets/img/struktur/')){
                mkdir('../assets/img/struktur/', 0777, true);
            }
            
            $file_bagan = 'struktur_'.time().'.'.$ext;
            if(move_uploaded_file($_FILES['file_bagan']['tmp_name'], '../assets/img/struktur/'.$file_bagan)){
                $sql = "INSERT INTO struktur_organisasi (judul, periode, file_bagan, keterangan, tgl_upload) VALUES (?,?,?,?,NOW())";
                $stmt = $conn->prepare($sql);
                if($stmt->execute([$judul, $periode, $file_bagan, $keterangan])){
                    $response = ['status' => 'sukses'];
                } else {
                    $response = ['status' => 'error', 'message' => 'Gagal simpan ke database'];
                }
            } else {
                $response = ['status' => 'error', 'message' => 'Gagal upload file'];
            }
        } else {
            $response = ['status' => 'error', 'message' => 'Format file harus JPG, PNG, atau PDF'];
        }
    } else {
        $response = ['status' => 'error', 'message' => 'Pilih file bagan dulu'];
    }
}

echo json_encode($response);
?>