<?php
header("Content-Type: application/json");
require_once "../config.php";

$response = ["status" => "error", "message" => "Unknown error"];
$departmentId = $_POST['id'] ?? $_GET['id'] ?? '';
$name = $_POST['name'] ?? '';
$code = $_POST['code'] ?? '';

//Insert Values
$newname = $_POST['newname'] ?? '';
$newcode = $_POST['newcode'] ?? '';

try {
    if ($departmentId && $name && $code) {
        // 🔹 Update Department
        $sql = "UPDATE tbldepartment 
                SET department_name = :name, department_code = :code 
                WHERE department_id = :id";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':code', $code);
        $stmt->bindParam(':id', $departmentId);

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Department updated successfully"];
        } else {
            $response = ["status" => "error", "message" => "Failed to update department"];
        }
    } else if ($newname && $newcode) {
        // 🔹 Insert Department
        $sql = "INSERT INTO tbldepartment (department_name, department_code) 
            VALUES (:newname, :newcode)";
        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':newname', $newname);
        $stmt->bindParam(':newcode', $newcode);

        if ($stmt->execute()) {
            $response = ["status" => "success", "message" => "Department inserted successfully"];
        } else {
            $response = ["status" => "error", "message" => "Failed to insert department"];
        }
    } else {
        // 🔹 Fetch all departments
        $sql = "SELECT department_id, department_name, department_code 
                FROM tbldepartment 
                ORDER BY department_name ASC";
        $stmt = $dbh->prepare($sql);
        $stmt->execute();

        $departments = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($departments) {
            $response = ["status" => "success", "data" => $departments];
        } else {
            $response = ["status" => "error", "message" => "No departments"];
        }
    }
} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
}

echo json_encode($response);
exit;
