<?php

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';


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

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/PdoCrud.php';

// Set up PdoCrud for the departments table
$crud = new PdoCrud($pdo, 'departments', 'id');

// Handle API requests
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        if (isset($_GET['id'])) {
            echo json_encode($crud->read($_GET['id']));
        } else {
            echo json_encode($crud->list());
        }
        break;

    case 'POST':
        try {
            $data = json_decode(file_get_contents('php://input'), true);
            if (!$data || !isset($data['name'])) {
                throw new Exception("Invalid input or missing department name.");
            }
            $id = $crud->create($data);
            echo json_encode(['id' => $id, 'message' => 'Department created successfully']);
        } catch (Exception $e) {
            http_response_code(400);
            echo json_encode(['error' => $e->getMessage()]);
        }
        break;

    case 'PUT':
        $data = json_decode(file_get_contents("php://input"), true);
        $id = $data['id'] ?? null;
        if ($id) {
            unset($data['id']);
            $crud->update($id, $data);
            echo json_encode(['status' => 'updated']);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Missing id']);
        }
        break;

    case 'DELETE':
        parse_str(file_get_contents("php://input"), $_DELETE);
        $id = $_DELETE['id'] ?? null;
        if ($id) {
            $crud->delete($id);
            echo json_encode(['status' => 'deleted']);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Missing id']);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}
