<?php

require_once __DIR__ . '/../library/auth.php'; 

allow_roles(['admin']);


$page_title = "Staff Attendance";

/*
|--------------------------------------------------------------------------
| PROCESSING
|--------------------------------------------------------------------------
*/

$school_id = $_SESSION['school_id'];
$current_session_id = get_current_session_id($pdo);
$message = '';

/*
|--------------------------------------------------------------------------
| SAVE ATTENDANCE
|--------------------------------------------------------------------------
*/

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

    $attendance_date = trim($_POST['attendance_date'] ?? '');
    $attendance_data = $_POST['attendance'] ?? [];
    $allowed_status = [

    'Present',
    'Absent',
    'Leave',
    'Half Day',
    'Holiday',
    'Weekly Off'

];

    if (!empty($attendance_date) && !empty($attendance_data)) {

        foreach ($attendance_data as $staff_id => $status) {
            $staff_id = (int)$staff_id;

            if (!in_array($status, $allowed_status, true)) {
                continue;
            }

            /*
            |--------------------------------------------------------------------------
            | VERIFY STAFF BELONGS TO SCHOOL
            |--------------------------------------------------------------------------
            */
            $verifyStmt = $pdo->prepare("
                SELECT id
                FROM teachers
                WHERE id = ?
                AND school_id = ?
                LIMIT 1
            ");

            $verifyStmt->execute([
                $staff_id,
                $school_id
            ]);

            $valid_staff = $verifyStmt->fetch(PDO::FETCH_ASSOC);

            if (!$valid_staff) {
                continue;
            }
			/*
|--------------------------------------------------------------------------
| CHECK HOLIDAY / WEEKLY OFF
|--------------------------------------------------------------------------
*/

$day_name = date(

    'l',

    strtotime($attendance_date)

);


/*
|--------------------------------------------------------------------------
| CHECK HOLIDAY
|--------------------------------------------------------------------------
*/

$holidayStmt = $pdo->prepare("

    SELECT title

    FROM holidays

    WHERE school_id = ?
    AND holiday_date = ?

    LIMIT 1

");

$holidayStmt->execute([

    $school_id,
    $attendance_date

]);

$holiday = $holidayStmt->fetch(PDO::FETCH_ASSOC);


/*
|--------------------------------------------------------------------------
| CHECK WEEKLY OFF
|--------------------------------------------------------------------------
*/

$weeklyStmt = $pdo->prepare("

    SELECT day_name

    FROM weekly_offs

    WHERE school_id = ?
    AND day_name = ?

    LIMIT 1

");

$weeklyStmt->execute([

    $school_id,
    $day_name

]);

$weekly_off = $weeklyStmt->fetch(PDO::FETCH_ASSOC);


/*
|--------------------------------------------------------------------------
| AUTO STATUS
|--------------------------------------------------------------------------
*/

if ($holiday) {

    $status = 'Holiday';
}

elseif ($weekly_off) {

    $status = 'Weekly Off';
}

            $remarks = trim($_POST['remarks'][$staff_id] ?? '');

            /*
            |--------------------------------------------------------------------------
            | CHECK EXISTING (सटीक चेकिंग - बिना session_id के)
            |--------------------------------------------------------------------------
            */
            $checkStmt = $pdo->prepare("
                SELECT id
                FROM staff_attendance
                WHERE school_id = ?
                AND staff_id = ?
                AND attendance_date = ?
                LIMIT 1
            ");

            $checkStmt->execute([
                $school_id,
                $staff_id,
                $attendance_date
            ]);

            $existing = $checkStmt->fetch(PDO::FETCH_ASSOC);

            /*
            |--------------------------------------------------------------------------
            | UPDATE
            |--------------------------------------------------------------------------
            */
            if ($existing) {

                $updateStmt = $pdo->prepare("
                    UPDATE staff_attendance
                    SET status = ?,
                        remarks = ?,
                        session_id = ?
                    WHERE id = ?
                    AND school_id = ?
                ");

                $updateStmt->execute([
                    $status,
                    $remarks,
                    $current_session_id, // अपडेट करते समय सेशन आईडी भी सेट कर देगा
                    $existing['id'],
                    $school_id
                ]);
            }

            /*
            |--------------------------------------------------------------------------
            | INSERT
            |--------------------------------------------------------------------------
            */
            else {

                $insertStmt = $pdo->prepare("
                    INSERT INTO staff_attendance
                    (
                        school_id,
                        session_id,
                        staff_id,
                        attendance_date,
                        status,
                        remarks
                    )
                    VALUES
                    (
                        ?, ?, ?, ?, ?, ?
                    )
                ");

                $insertStmt->execute([
                    $school_id,
                    $current_session_id,
                    $staff_id,
                    $attendance_date,
                    $status,
                    $remarks
                ]);
            }
        }

        $message = "Attendance Saved Successfully";
    }
}

/*
|--------------------------------------------------------------------------
| FETCH STAFF USERS
|--------------------------------------------------------------------------
*/

$staffStmt = $pdo->prepare("
    SELECT
    id,
    name,
    salary
FROM teachers
WHERE school_id = ?
AND status = 'Active'
ORDER BY name ASC
");

$staffStmt->execute([$school_id]);

$staff_users = $staffStmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';

?>
<div class="content-wrapper">

    <!-- PAGE HEADER -->

    <section class="content-header">

        <div class="container-fluid">

            <div class="row mb-3">

                <div class="col-sm-6">

                    <h1 class="m-0">

                        Staff Attendance

                    </h1>

                </div>

                <div class="col-sm-6 text-right">

                    <a href="view_staff_attendance.php"
                       class="btn btn-info">

                        <i class="fas fa-eye"></i>

                        View Attendance

                    </a>

                </div>

            </div>

        </div>

    </section>

    <!-- MAIN CONTENT -->

    <section class="content">

        <div class="container-fluid">

            <!-- SUCCESS MESSAGE -->

            <?php if (!empty($message)): ?>

                <div class="alert alert-success alert-dismissible fade show">

                    <button type="button"
                            class="close"
                            data-dismiss="alert">

                        &times;

                    </button>

                    <?php echo htmlspecialchars($message); ?>

                </div>

            <?php endif; ?>

            <!-- CARD -->

            <div class="card card-outline card-primary shadow-sm">

                <!-- CARD HEADER -->

                <div class="card-header">

                    <h3 class="card-title">

                        Mark Staff Attendance

                    </h3>

                </div>

                <!-- FORM -->

                <form method="POST">

                    <div class="card-body">

                        <!-- DATE -->

                        <div class="row mb-4">

                            <div class="col-md-4">

                                <label>

                                    Attendance Date

                                </label>

                                <input
                                    type="date"
                                    name="attendance_date"
                                    class="form-control" max="<?= date('Y-m-d') ?>"
                                    required
                                    value="<?php echo htmlspecialchars($attendance_date ?? date('Y-m-d')); ?>"
                                >

                            </div>

                        </div>
						<?php

$selected_date =
    $attendance_date ?? date('Y-m-d');

$day_name =
    date('l', strtotime($selected_date));

/*
|--------------------------------------------------------------------------
| HOLIDAY CHECK
|--------------------------------------------------------------------------
*/

$stmtHoliday = $pdo->prepare("

    SELECT title

    FROM holidays

    WHERE school_id = ?
    AND holiday_date = ?

    LIMIT 1

");

$stmtHoliday->execute([

    $school_id,
    $selected_date

]);

$holidayData =
    $stmtHoliday->fetch(PDO::FETCH_ASSOC);


/*
|--------------------------------------------------------------------------
| WEEKLY OFF CHECK
|--------------------------------------------------------------------------
*/

$stmtWeekly = $pdo->prepare("

    SELECT id

    FROM weekly_offs

    WHERE school_id = ?
    AND day_name = ?

    LIMIT 1

");

$stmtWeekly->execute([

    $school_id,
    $day_name

]);

$weeklyData =
    $stmtWeekly->fetch(PDO::FETCH_ASSOC);

?>


<?php if ($holidayData): ?>

    <div class="alert alert-primary">

        <i class="fas fa-calendar-alt"></i>

        Holiday Detected:
        <strong>

            <?php echo htmlspecialchars($holidayData['title']); ?>

        </strong>

        <br>

        Attendance will be automatically marked as Holiday.

    </div>

<?php elseif ($weeklyData): ?>

    <div class="alert alert-dark">

        <i class="fas fa-bed"></i>

        Weekly Off Detected:
        <strong>

            <?php echo htmlspecialchars($day_name); ?>

        </strong>

        <br>

        Attendance will be automatically marked as Weekly Off.

    </div>

<?php endif; ?>

                        <!-- TABLE -->

                        <div class="table-responsive">

    <table class="table table-bordered table-hover table-striped">

        <thead class="thead-dark">

            <tr>

                <th width="60">#</th>

                <th>Teacher Name</th>

                <th>Monthly Salary</th>

                <th width="220">Attendance Status</th>

                <th>Remarks</th>

            </tr>

        </thead>

        <tbody>

            <?php if (!empty($staff_users)): ?>

                <?php foreach ($staff_users as $index => $staff): ?>

                    <tr>

                        <!-- SERIAL -->

                        <td>

                            <?php echo $index + 1; ?>

                        </td>

                        <!-- TEACHER NAME -->

                        <td>

                            <strong>

                                <?php echo htmlspecialchars($staff['name']); ?>

                            </strong>

                        </td>

                        <!-- SALARY -->

                        <td>

                            <span class="badge badge-success p-2">

                                ₹<?php echo number_format($staff['salary'], 2); ?>

                            </span>

                        </td>

                                                <!-- STATUS -->

                                                <td>

                                                   <select
    name="attendance[<?php echo $staff['id']; ?>]"
    class="form-control"

    <?php

    $selected_date =
        $attendance_date ?? date('Y-m-d');

    $day_name =
        date('l', strtotime($selected_date));

    $is_holiday = false;

    $is_weekly_off = false;

    /*
    |--------------------------------------------------------------------------
    | CHECK HOLIDAY
    |--------------------------------------------------------------------------
    */

    $stmtHoliday = $pdo->prepare("

        SELECT id

        FROM holidays

        WHERE school_id = ?
        AND holiday_date = ?

        LIMIT 1

    ");

    $stmtHoliday->execute([

        $school_id,
        $selected_date

    ]);

    $is_holiday =
        $stmtHoliday->fetch(PDO::FETCH_ASSOC);

    /*
    |--------------------------------------------------------------------------
    | CHECK WEEKLY OFF
    |--------------------------------------------------------------------------
    */

    $stmtWeekly = $pdo->prepare("

        SELECT id

        FROM weekly_offs

        WHERE school_id = ?
        AND day_name = ?

        LIMIT 1

    ");

    $stmtWeekly->execute([

        $school_id,
        $day_name

    ]);

    $is_weekly_off =
        $stmtWeekly->fetch(PDO::FETCH_ASSOC);

    if ($is_holiday || $is_weekly_off) {

        echo 'disabled';
    }

    ?>

    required
>

                                                        <option value="Present">

                                                            Present

                                                        </option>

                                                        <option value="Absent">

                                                            Absent

                                                        </option>

                                                        <option value="Leave">

                                                            Leave

                                                        </option>

                                                        <option value="Half Day">

                                                            Half Day

                                                        </option>

                                                    </select>

                                                </td>

                                                <!-- REMARKS -->

                                                <td>

                                                    <input
                                                        type="text"
                                                        name="remarks[<?php echo $staff['id']; ?>]"
                                                        class="form-control"
                                                        placeholder="Optional Remarks"
                                                    >

                                                </td>

                                            </tr>

                                        <?php endforeach; ?>

                                    <?php else: ?>

                                        <tr>

                                            <td colspan="6"
                                                class="text-center text-muted">

                                                No Staff Found

                                            </td>

                                        </tr>

                                    <?php endif; ?>

                                </tbody>

                            </table>

                        </div>

                    </div>

                    <!-- FOOTER -->

                    <div class="card-footer text-right">

                        <button type="submit"
                                class="btn btn-primary">

                            <i class="fas fa-save"></i>

                            Save Attendance

                        </button>

                    </div>

                </form>

            </div>

        </div>

    </section>

</div>

<?php
require_once __DIR__ . '/../include/footer.php';
?>