<?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();

$id = $_POST['id']?? '';
$judul = $_POST['judul'];
$periode = $_POST['periode'];
$keterangan = $_POST['keterangan']?? '';

$file_bagan = $_POST['file_lama']?? '';

// Upload file baru kalo ada
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'])){
        // Hapus file lama kalo edit
        if($id && $file_bagan && file_exists('../assets/img/struktur/'.$file_bagan)){
            unlink('../assets/img/struktur/'.$file_bagan);
        }
        
        if(!is_dir('../assets/img/struktur/')) mkdir('../assets/img/struktur/', 0777, true);
        $file_bagan = 'struktur_'.time().'.'.$ext;
        move_uploaded_file($_FILES['file_bagan']['tmp_name'], '../assets/img/struktur/'.$file_bagan);
    } else {
        echo json_encode(['status'=>'error','message'=>'Format file harus JPG, PNG, atau PDF']);
        exit;
    }
}

if($id){ // UPDATE
    $sql = "UPDATE struktur_organisasi SET judul=?, periode=?, keterangan=?, file_bagan=? WHERE id=?";
    $params = [$judul, $periode, $keterangan, $file_bagan, $id];
    $msg = 'Data struktur berhasil diupdate';
} else { // INSERT
    if(!$file_bagan){
        echo json_encode(['status'=>'error','message'=>'File bagan wajib diupload']);
        exit;
    }
    $sql = "INSERT INTO struktur_organisasi (judul, periode, keterangan, file_bagan, tgl_upload) VALUES (?,?,?,?,NOW())";
    $params = [$judul, $periode, $keterangan, $file_bagan];
    $msg = 'Data struktur berhasil ditambahkan';
}

$stmt = $conn->prepare($sql);
if($stmt->execute($params)){
    echo json_encode(['status'=>'success','message'=>$msg]);
} else {
    echo json_encode(['status'=>'error','message'=>'Gagal simpan data']);
}
?>