<?php

session_start();
require 'config.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Release the session lock on plain page views; the POST handling below still
// needs to write session data (new_user_created), so it keeps the session
// open for itself.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    session_write_close();
}

// ---------------------------
// LOAD SHIFTS
// ---------------------------
$shifts = [];
$res = $conn->query("SELECT * FROM shifts ORDER BY name");

while ($row = $res->fetch_assoc()) {
    $checkin = strtotime($row['checkin']);
    $checkout = strtotime($row['checkout']);

    if (!empty($row['crosses_midnight']) && $checkout < $checkin) {
        $checkout += 86400;
    }

    $hours = ($checkin && $checkout) ? ($checkout - $checkin) / 3600 : 0;
    $row['total_hours'] = round($hours, 2);
    $shifts[$row['id']] = $row;
}

// ---------------------------
// LOAD EMPLOYEES
// ---------------------------
$employees = [];
$res = $conn->query("
    SELECT 
        e.id,
        e.name,
        e.shift_id,
        e.role,
        e.user_id,
        e.department_id,
        e.group_id,
        s.name AS shift_name
    FROM employees e
    LEFT JOIN shifts s 
        ON s.id = e.shift_id
    ORDER BY e.name
");

while ($row = $res->fetch_assoc()) {
    // Convert comma-separated string from DB into clean arrays for front-end checkboxes
    $row['department_ids'] = !empty($row['department_id']) ? explode(',', $row['department_id']) : [];
    $row['group_ids'] = !empty($row['group_id']) ? explode(',', $row['group_id']) : [];
    $employees[$row['id']] = $row;
}

// ---------------------------
// LOAD DEPARTMENTS
// ---------------------------
$departments = [];
$res = $conn->query("SELECT * FROM departments ORDER BY name");

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

// ---------------------------
// LOAD GROUPS
// ---------------------------
$groups = [];
$res = $conn->query("SELECT * FROM `groups` ORDER BY name"); // Backticks used as 'groups' can be a SQL reserved keyword

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

// ---------------------------
// EXCEPTIONS
// ---------------------------
$exceptions = [];
$res = $conn->query("
    SELECT employee_id, checkin, checkout
    FROM exceptions
");

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

// ---------------------------
// HANDLE POST
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // DELETE SHIFT
    if (!empty($_POST['delete_shift_id'])) {
        $shiftId = intval($_POST['delete_shift_id']);

        $stmt = $conn->prepare("SELECT COUNT(*) FROM employees WHERE shift_id = ?");
        $stmt->bind_param("i", $shiftId);
        $stmt->execute();
        $stmt->bind_result($count);
        $stmt->fetch();
        $stmt->close();

        if ($count > 0) {
            header("Location: settings.php?error=shift_in_use");
            exit;
        }

        $stmt = $conn->prepare("DELETE FROM shifts WHERE id = ?");
        $stmt->bind_param("i", $shiftId);
        $stmt->execute();
        $stmt->close();

        header("Location: settings.php?deleted=1");
        exit;
    }

    // CREATE SHIFT
    if (!empty($_POST['new_shift_name'])) {
        $stmt = $conn->prepare("
            INSERT INTO shifts (name, checkin, checkout, crosses_midnight, color)
            VALUES (?, ?, ?, ?, ?)
        ");

        $cross = isset($_POST['new_shift_cross']) ? 1 : 0;
        $newName = $_POST['new_shift_name'];
        $newCheckin = $_POST['new_shift_checkin'];
        $newCheckout = $_POST['new_shift_checkout'];
        $newColor = $_POST['new_shift_color'];

        $stmt->bind_param("sssis", $newName, $newCheckin, $newCheckout, $cross, $newColor);
        $stmt->execute();
        $stmt->close();

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

    // EDIT SHIFT
    if (!empty($_POST['edit_shift_id'])) {
        $stmt = $conn->prepare("
            UPDATE shifts
            SET name = ?, checkin = ?, checkout = ?, crosses_midnight = ?, color = ?
            WHERE id = ?
        ");

        $cross = isset($_POST['edit_shift_cross']) ? 1 : 0;
        $editName = $_POST['edit_shift_name'];
        $editCheckin = $_POST['edit_shift_checkin'];
        $editCheckout = $_POST['edit_shift_checkout'];
        $editColor = $_POST['edit_shift_color'];
        $editId = (int)$_POST['edit_shift_id'];

        $stmt->bind_param("sssisi", $editName, $editCheckin, $editCheckout, $cross, $editColor, $editId);
        $stmt->execute();
        $stmt->close();

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

    // ---------------------------
    // ASSIGN EMPLOYEES (MATRIX SYNC)
    // ---------------------------
    if (isset($_POST['save_assignments'])) {
        $createdUsers = [];

        foreach ($employees as $empId => $emp) {
            $shiftId = $_POST['employee_shift'][$empId] ?? null;
            $role = $_POST['employee_role'][$empId] ?? "staff";
            
            // Gather array/value of checked departments & groups explicitly for THIS employee ID
            $checkedDepts = $_POST['employee_departments'][$empId] ?? [];
            $checkedGroups = $_POST['employee_groups'][$empId] ?? [];
            
            $shiftId = ($shiftId === "" || $shiftId === null) ? null : (int)$shiftId;
            
            // Format array to clean comma-separated string, or null if nothing selected
            if (is_array($checkedDepts)) {
                $dbDepartmentField = !empty($checkedDepts) ? implode(',', array_map('intval', $checkedDepts)) : null;
            } else {
                $dbDepartmentField = !empty($checkedDepts) ? (string)intval($checkedDepts) : null;
            }

            if (is_array($checkedGroups)) {
                $dbGroupField = !empty($checkedGroups) ? implode(',', array_map('intval', $checkedGroups)) : null;
            } else {
                $dbGroupField = !empty($checkedGroups) ? (string)intval($checkedGroups) : null;
            }

            if (!in_array($role, ['manager', 'supervisor', 'staff'])) {
                $role = 'staff';
            }

            $userId = $emp['user_id'];
            $empName = $emp['name'];

            // ---------------------------
            // CREATE USER MANAGEMENT PROFILE
            // ---------------------------
            if (($role === 'manager' || $role === 'supervisor') && !$userId && !isset($createdUsers[$empId])) {
                $createdUsers[$empId] = true;

                $base = strtolower(str_replace(' ', '.', $empName));
                $username = $base;
                $i = 1;

                $checkStmt = $conn->prepare("SELECT id FROM users WHERE username=?");

                while (true) {
                    $checkStmt->bind_param("s", $username);
                    $checkStmt->execute();
                    $checkStmt->store_result();

                    if ($checkStmt->num_rows === 0) break;

                    $username = $base . $i;
                    $i++;
                }
                $checkStmt->close();

                $plainPassword = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 8);
                $hashed = password_hash($plainPassword, PASSWORD_DEFAULT);

                $stmt = $conn->prepare("
                    INSERT INTO users (username, password, role, department_id, must_change_password)
                    VALUES (?, ?, ?, ?, 1)
                ");
                
                // Track primary team context (First checked element index)
                $userDeptId = is_array($checkedDepts) && !empty($checkedDepts) ? (int)$checkedDepts[0] : (!empty($checkedDepts) ? (int)$checkedDepts : null);

                $stmt->bind_param("sssi", $username, $hashed, $role, $userDeptId);
                $stmt->execute();

                $userId = $stmt->insert_id;
                $stmt->close();

                $_SESSION['new_user_created'] = [
                    'username' => $username,
                    'password' => $plainPassword,
                    'name' => $empName
                ];
            }

            // ---------------------------
            // MATRIX PERSISTENCE UPDATE
            // ---------------------------
            $stmt = $conn->prepare("
                UPDATE employees 
                SET shift_id = ?, role = ?, department_id = ?, group_id = ?, user_id = ? 
                WHERE id = ?
            ");

            $stmt->bind_param(
                "isssii",
                $shiftId,
                $role,
                $dbDepartmentField, 
                $dbGroupField,
                $userId,
                $empId
            );

            $stmt->execute();
            $stmt->close();
        }
    }

    // ---------------------------
    // EXCEPTIONS
    // ---------------------------
    if (isset($_POST['save_exceptions'])) {
        $conn->query("TRUNCATE TABLE exceptions");

        if (!empty($_POST['exception_employee'])) {
            $stmt = $conn->prepare("
                INSERT INTO exceptions (employee_id, checkin, checkout)
                VALUES (?, ?, ?)
            ");

            foreach ($_POST['exception_employee'] as $i => $empId) {
                $empId = intval($empId);

                if ($empId) {
                    $stmt->bind_param(
                        "iss",
                        $empId,
                        $_POST['exception_checkin'][$i],
                        $_POST['exception_checkout'][$i]
                    );
                    $stmt->execute();
                }
            }
            $stmt->close();
        }
    }

    // ---------------------------
    // AJAX RESPONSE ENGINE
    // ---------------------------
    $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

    if ($isAjax) {
        header('Content-Type: application/json');
        $response = ["status" => "success"];

        if (!empty($_SESSION['new_user_created'])) {
            $response["new_user"] = $_SESSION['new_user_created'];
        }

        echo json_encode($response);
        unset($_SESSION['new_user_created']);
        exit;
    }

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