<?php

require_once '../config/config.php';
require_once '../classes/SubDepartment.php';

$subDeptObj = new SubDepartment($conn);

$action = $_POST['action'] ?? '';
$response = ['status' => 'error', 'message' => 'Invalid action'];

switch ($action) {
    case 'add':
        $subdeptData = [
            'subdept_name' => trim($_POST['subdept_name']),
            'dept_id' => intval($_POST['dept_id'])
        ];
        $result = $subDeptObj->addSubDepartment($subdeptData);
        if ($result)
            $response = ['status' => 'success', 'message' => 'Subdepartment Added Successfully'];
        else
            $response = ['status' => 'error', 'message' => 'Failed to add subdepartment'];
        break;

    case 'edit':
        $subdeptData = [
            'subdept_id' => intval($_POST['id']),
            'subdept_name' => trim($_POST['subdept_name']),
            'dept_id' => intval($_POST['dept_id'])
        ];
        if ($subDeptObj->updateSubDepartment($subdeptData))
            $response = ['status' => 'success', 'message' => 'Subdepartment Updated Successfully'];
        else
            $response = ['status' => 'error', 'message' => 'Failed to update subdepartment'];
        break;

    case 'delete':
        $id = intval($_POST['id']);
        if ($subDeptObj->delete($id))
            $response = ['status' => 'success', 'message' => "Subdepartment Deleted"];
        else
            $response = ['status' => 'error', 'message' => "Failed to delete subdepartment"];
        break;

    case 'get':
        $id = intval($_POST['id']);
        $subdept = $subDeptObj->getSubDepartmentById($id);
        if ($subdept)
            $response = ['status' => 'success', 'subdept' => $subdept];
        else
            $response = ['status' => '', 'message' => 'Subdepartment not found'];
        break;

    case 'list':
        $subdepartments = $subDeptObj->getAllSubDepartments();
        $response = ['status' => 'success', 'subdepartments' => $subdepartments];
        break;
}

echo json_encode($response);
