<?php
session_start();
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);
ob_start();

include '../config/database.php';
$db = new Database();
$conn = $db->getConnection();

$action = $_REQUEST['action']?? 'get';
$response = ['status' => 'error', 'message' => 'Aksi tidak dikenal'];

try {
    if($action == 'get'){
        $stmt = $conn->prepare("SELECT * FROM pengurus_dpw ORDER BY urutan ASC, id ASC");
        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $response = ['status'=>'success', 'data'=>$data];

    } elseif($action == 'simpan'){
        $id = $_POST['id']?? '';
        $nama_lengkap = trim($_POST['nama_lengkap']?? '');
        $jabatan = $_POST['jabatan']?? '';
        $no_hp = $_POST['no_hp']?? '';
        $email = $_POST['email']?? '';
        $periode_mulai = $_POST['periode_mulai']?? date('Y');
        $periode_selesai = $_POST['periode_selesai']?? date('Y');
        $status = $_POST['status']?? 'Aktif';
        $urutan = $_POST['urutan']?? 0;

        if(empty($nama_lengkap)) throw new Exception('Nama Lengkap wajib diisi');
        if(empty($jabatan)) throw new Exception('Jabatan wajib dipilih');

        $foto = $_POST['foto_lama']?? 'default.png';
        if(isset($_FILES['foto']) && $_FILES['foto']['error'] == 0){
            $folder = '../assets/img/pengurus/';
            if(!is_dir($folder)) mkdir($folder, 0777, true);
            if($_FILES['foto']['size'] > 2097152) throw new Exception('Ukuran foto max 2MB');

            $ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg','jpeg','png','gif','webp'];
            if(!in_array($ext, $allowed)) throw new Exception('Format foto harus JPG/PNG/GIF/WEBP');

            $foto = 'pengurus_'.time().'_'.rand(100,999).'.'.$ext;
            if(!move_uploaded_file($_FILES['foto']['tmp_name'], $folder.$foto)){
                throw new Exception('Gagal upload foto');
            }
        }

        if(empty($id)){
            $stmt = $conn->prepare("INSERT INTO pengurus_dpw (nama_lengkap, jabatan, no_hp, email, periode_mulai, periode_selesai, foto, urutan, status) VALUES (?,?,?,?,?,?,?,?,?)");
            $stmt->execute([$nama_lengkap, $jabatan, $no_hp, $email, $periode_mulai, $periode_selesai, $foto, $urutan, $status]);
            $msg = 'Pengurus berhasil ditambah';
        } else {
            $stmt = $conn->prepare("UPDATE pengurus_dpw SET nama_lengkap=?, jabatan=?, no_hp=?, email=?, periode_mulai=?, periode_selesai=?, foto=?, urutan=?, status=? WHERE id=?");
            $stmt->execute([$nama_lengkap, $jabatan, $no_hp, $email, $periode_mulai, $periode_selesai, $foto, $urutan, $status, $id]);
            $msg = 'Pengurus berhasil diupdate';
        }
        $response = ['status'=>'sukses', 'message'=>$msg];

    } elseif($action == 'hapus'){
        $id = $_POST['id'];
        $stmt = $conn->prepare("SELECT foto FROM pengurus_dpw WHERE id=?");
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        if($row && $row['foto']!= 'default.png'){
            @unlink('../assets/img/pengurus/'.$row['foto']);
        }
        $stmt = $conn->prepare("DELETE FROM pengurus_dpw WHERE id=?");
        $stmt->execute([$id]);
        $response = ['status'=>'sukses', 'message'=>'Pengurus berhasil dihapus'];

    } elseif($action == 'detail'){
        $id = $_GET['id'];
        $stmt = $conn->prepare("SELECT * FROM pengurus_dpw WHERE id=?");
        $stmt->execute([$id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        $response = ['status'=>'success', 'data'=>$data];
    }

} catch (Exception $e) {
    $response = ['status'=>'error', 'message'=>$e->getMessage()];
}

ob_end_clean();
echo json_encode($response);
?>