<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

require '../config.php';
if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    session_start();
}

$userRole = strtolower($_SESSION['role'] ?? '');

if (!in_array($userRole, ['hr', 'admin', 'superadmin'])) {
    die("Access Denied");
}

// --- DELETE HANDLER ---
if (isset($_GET['delete'])) {
    $deleteId = intval($_GET['delete']);
    
    $stmt = $conn->prepare("DELETE FROM leave_types WHERE id = ?");
    $stmt->bind_param("i", $deleteId);
    $stmt->execute();
    
    header("Location: leave_types.php");
    exit;
}

// --- SUBMIT PROCESSOR (INSERT / UPDATE) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = trim($_POST['name']);
    $days = intval($_POST['days_allowed']);
    $paid = intval($_POST['is_paid']);
    $id = isset($_POST['id']) ? intval($_POST['id']) : null;

    if ($id) {
        // Handle Update Execution
        $stmt = $conn->prepare("UPDATE leave_types SET name = ?, days_allowed = ?, is_paid = ? WHERE id = ?");
        $stmt->bind_param("siii", $name, $days, $paid, $id);
    } else {
        // Handle New Insertion Execution
        $stmt = $conn->prepare("INSERT INTO leave_types (name, days_allowed, is_paid) VALUES (?, ?, ?)");
        $stmt->bind_param("sii", $name, $days, $paid);
    }

    $stmt->execute();
    header("Location: leave_types.php");
    exit;
}

// --- EDIT HANDLER (POPULATING FORM) ---
$editMode = false;
$editData = [];

if (isset($_GET['edit'])) {
    $editId = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM leave_types WHERE id = ?");
    $stmt->bind_param("i", $editId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $editMode = true;
        $editData = $row;
    }
}

// --- DATA READ GENERATOR ---
$types = [];
$res = $conn->query("SELECT * FROM leave_types ORDER BY name");
while ($row = $res->fetch_assoc()) {
    $types[] = $row;
}
?>