<?php
session_start();
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    jsonResponse(false, 'Unauthorized');
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

switch ($action) {
    case 'get_categories':
        getCategories();
        break;
    
    case 'get_layanan':
        getLayanan();
        break;
    
    case 'get_layanan_active':
        getLayananActive();
        break;
    
    case 'add_category':
        requireAdmin();
        addCategory();
        break;
    
    case 'add_layanan':
        requireAdmin();
        addLayanan();
        break;
    
    case 'update_layanan':
        requireAdmin();
        updateLayanan();
        break;
    
    case 'delete_layanan':
        requireAdmin();
        deleteLayanan();
        break;
    
    default:
        jsonResponse(false, 'Invalid action');
}

function getCategories() {
    try {
        $result = query("SELECT * FROM kategori_layanan ORDER BY nama_kategori ASC", []);
        $categories = [];
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }
        jsonResponse(true, 'Success', $categories);
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function getLayanan() {
    try {
        $sql = "SELECT l.*, k.nama_kategori as kategori_nama 
                FROM layanan l 
                JOIN kategori_layanan k ON l.id_kategori = k.id 
                ORDER BY k.nama_kategori ASC, l.nama_layanan ASC";
        $result = query($sql, []);
        $layanan = [];
        while ($row = $result->fetch_assoc()) {
            $layanan[] = $row;
        }
        jsonResponse(true, 'Success', $layanan);
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function getLayananActive() {
    try {
        $sql = "SELECT l.*, k.nama_kategori as kategori_nama 
                FROM layanan l 
                JOIN kategori_layanan k ON l.id_kategori = k.id 
                WHERE l.status = 'active'
                ORDER BY k.nama_kategori ASC, l.nama_layanan ASC";
        $result = query($sql, []);
        $layanan = [];
        while ($row = $result->fetch_assoc()) {
            $layanan[] = $row;
        }
        jsonResponse(true, 'Success', $layanan);
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function addCategory() {
    try {
        $nama_kategori = clean($_POST['nama_kategori'] ?? '');
        
        if (empty($nama_kategori)) {
            jsonResponse(false, 'Nama kategori harus diisi');
        }
        
        $sql = "INSERT INTO kategori_layanan (nama_kategori) VALUES (?)";
        insert($sql, [$nama_kategori], 's');
        
        jsonResponse(true, 'Kategori berhasil ditambahkan');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function addLayanan() {
    try {
        $id_kategori = clean($_POST['id_kategori'] ?? '');
        $nama_layanan = clean($_POST['nama_layanan'] ?? '');
        $harga = clean($_POST['harga'] ?? '');
        $status = clean($_POST['status'] ?? 'active');
        
        if (empty($id_kategori) || empty($nama_layanan) || empty($harga)) {
            jsonResponse(false, 'Semua field harus diisi');
        }
        
        $sql = "INSERT INTO layanan (id_kategori, nama_layanan, harga, status) VALUES (?, ?, ?, ?)";
        insert($sql, [$id_kategori, $nama_layanan, $harga, $status], 'isds');
        
        jsonResponse(true, 'Layanan berhasil ditambahkan');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function updateLayanan() {
    try {
        $id = clean($_POST['id'] ?? '');
        $id_kategori = clean($_POST['id_kategori'] ?? '');
        $nama_layanan = clean($_POST['nama_layanan'] ?? '');
        $harga = clean($_POST['harga'] ?? '');
        $status = clean($_POST['status'] ?? 'active');
        
        if (empty($id) || empty($id_kategori) || empty($nama_layanan) || empty($harga)) {
            jsonResponse(false, 'Semua field harus diisi');
        }
        
        $sql = "UPDATE layanan SET id_kategori = ?, nama_layanan = ?, harga = ?, status = ? WHERE id = ?";
        execute($sql, [$id_kategori, $nama_layanan, $harga, $status, $id], 'isdsi');
        
        jsonResponse(true, 'Layanan berhasil diupdate');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function deleteLayanan() {
    try {
        $id = clean($_POST['id'] ?? '');
        
        if (empty($id)) {
            jsonResponse(false, 'ID tidak valid');
        }
        
        // Soft delete - ubah status menjadi inactive
        $sql = "UPDATE layanan SET status = 'inactive' WHERE id = ?";
        execute($sql, [$id], 'i');
        
        jsonResponse(true, 'Layanan berhasil dihapus');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}
?>
