<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require '../config.php';
session_start();

$userId      = $_SESSION['user_id'] ?? null;
$userRole    = strtolower(trim($_SESSION['role'] ?? ''));
$userDeptId  = $_SESSION['department_id'] ?? null;

// =====================================================
// ADD EMPLOYEE TO MANAGER DEPARTMENT (AJAX SAFE)
// =====================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_employee_to_department'])) {

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

    if ($userRole !== 'manager') {
        http_response_code(403);
        echo json_encode(["status" => "error", "message" => "Unauthorized"]);
        exit;
    }

    $empId = intval($_POST['add_employee_to_department']);

    $stmt = $conn->prepare("SELECT department_id FROM employees WHERE id = ?");
    $stmt->bind_param("i", $empId);
    $stmt->execute();
    $stmt->bind_result($currentDept);
    $stmt->fetch();
    $stmt->close();

    if (!$currentDept) {
        echo json_encode(["status" => "error", "message" => "Employee not found"]);
        exit;
    }

    if ($currentDept == $userDeptId) {
        echo json_encode(["status" => "exists"]);
        exit;
    }

    $update = $conn->prepare("
        UPDATE employees 
        SET department_id = ? 
        WHERE id = ?
    ");

    $update->bind_param("ii", $userDeptId, $empId);
    $update->execute();
    $update->close();

    echo json_encode(["status" => "success"]);
    exit;
}

// =====================================================
// DEPARTMENTS
// =====================================================
$departments = [];

if ($userRole === 'manager') {

    $stmt = $conn->prepare("SELECT * FROM departments WHERE id = ? ORDER BY name");
    $stmt->bind_param("i", $userDeptId);
    $stmt->execute();
    $res = $stmt->get_result();

} else {
    $res = $conn->query("SELECT * FROM departments ORDER BY name");
}

while ($row = $res->fetch_assoc()) {
    $departments[$row['id']] = $row;
}

// =====================================================
// SHIFTS
// =====================================================
$shifts = [];
$res = $conn->query("SELECT id, name, checkin, checkout FROM shifts ORDER BY name");

while ($row = $res->fetch_assoc()) {
    $shifts[$row['id']] = $row;
}

// =====================================================
// EMPLOYEES (FLAT LIST - IMPORTANT)
// =====================================================
$employees = [];

if ($userRole === 'manager') {

    $stmt = $conn->prepare("
        SELECT id, name, department_id 
        FROM employees 
        WHERE department_id = ?
        ORDER BY name
    ");

    $stmt->bind_param("i", $userDeptId);
    $stmt->execute();
    $res = $stmt->get_result();

} else {

    $res = $conn->query("
        SELECT id, name, department_id 
        FROM employees 
        ORDER BY name
    ");
}

while ($row = $res->fetch_assoc()) {
    $employees[] = $row;
}

// =====================================================
// SHIFT SETTINGS
// =====================================================
$deptDefaults = [];
$employeeOverrides = [];

if ($userRole === 'manager') {

    $stmt = $conn->prepare("
        SELECT * FROM department_shifts
        WHERE department_id = ?
    ");

    $stmt->bind_param("i", $userDeptId);
    $stmt->execute();
    $res = $stmt->get_result();

} else {
    $res = $conn->query("SELECT * FROM department_shifts");
}

while ($row = $res->fetch_assoc()) {

    if ($row['employee_id'] === null) {
        $deptDefaults[$row['department_id']] = $row['shift_id'];
    } else {
        $employeeOverrides[$row['employee_id']] = $row['shift_id'];
    }
}

// =====================================================
// MAIN FORM SUBMIT (SAFE SEPARATION FROM AJAX)
// =====================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['add_employee_to_department'])) {

    // Department shifts
    if (!empty($_POST['dept_shift'])) {

        $stmt = $conn->prepare("
            INSERT INTO department_shifts (department_id, shift_id, employee_id)
            VALUES (?, ?, NULL)
            ON DUPLICATE KEY UPDATE shift_id = VALUES(shift_id)
        ");

        foreach ($_POST['dept_shift'] as $deptId => $shiftId) {

            $deptId = intval($deptId);
            $shiftId = intval($shiftId);

            if ($userRole === 'manager' && $deptId != $userDeptId) continue;

            $stmt->bind_param("ii", $deptId, $shiftId);
            $stmt->execute();
        }

        $stmt->close();
    }

    // Employee overrides
    if (!empty($_POST['employee_shift_override'])) {

        $getDept = $conn->prepare("SELECT department_id FROM employees WHERE id = ?");

        $insert = $conn->prepare("
            INSERT INTO department_shifts (department_id, shift_id, employee_id)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE shift_id = VALUES(shift_id)
        ");

        foreach ($_POST['employee_shift_override'] as $empId => $shiftId) {

            $empId = intval($empId);
            $shiftId = intval($shiftId);

            $getDept->bind_param("i", $empId);
            $getDept->execute();
            $getDept->bind_result($deptId);
            $getDept->fetch();
            $getDept->free_result();

            if (!$deptId) continue;

            if ($userRole === 'manager' && $deptId != $userDeptId) continue;

            $insert->bind_param("iii", $deptId, $shiftId, $empId);
            $insert->execute();
        }

        $getDept->close();
        $insert->close();
    }

    header("Location: department_settings.php?saved=1");
    exit;
}
?>