<?php
session_start();
error_reporting(0);
include('includes/config.php');
date_default_timezone_set('Asia/Kolkata');

if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}

// Handle update out time action
if (isset($_GET['updateout'])) {
    $id = intval($_GET['updateout']);
    $current_time = date('Y-m-d H:i:s');

    $sql = "UPDATE inout_records SET out_time = :out_time WHERE id = :id";
    $query = $dbh->prepare($sql);
    $query->bindParam(':out_time', $current_time, PDO::PARAM_STR);
    $query->bindParam(':id', $id, PDO::PARAM_INT);

    if ($query->execute()) {
        $_SESSION['updatemsg'] = "Out time updated successfully";
    } else {
        $_SESSION['error'] = "Failed to update out time";
    }
    header('location:manage-inout-records.php');
    exit;
}

// ---------------- Date Filter Logic ---------------- //
$fromDate = !empty($_GET['from']) ? $_GET['from'] : date('Y-m-d');
$toDate = !empty($_GET['to']) ? $_GET['to'] : date('Y-m-d');

$sql = "SELECT * FROM inout_records 
        WHERE DATE(in_time) BETWEEN :fromDate AND :toDate 
        ORDER BY in_time DESC";
$query = $dbh->prepare($sql);
$query->bindParam(':fromDate', $fromDate, PDO::PARAM_STR);
$query->bindParam(':toDate', $toDate, PDO::PARAM_STR);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Manage In/Out Records | Library System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">

    <!-- ✅ Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- ✅ DataTables Bootstrap 5 -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">

    <!-- ✅ FontAwesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- Select2 -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <style>
        .square-card {
            width: 100%;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
            border-radius: 5px;
        }

        .flash-message {
            max-width: 600px;
            margin: 0 auto 15px;
        }

        .table-wrapper {
            overflow-x: auto;
            padding: 10px;
        }

        .col-md-12 h5 {
            color:   #0d6efd;
            font-size: 20px;
        }

        .dataTables_filter label {
            color: #000 !important;
            font-weight: 500;
        }

        .dataTables_filter input {
            height: 32px;
            font-size: 0.95rem;
            padding: 4px 8px;
        }
    </style>
</head>

<body>

    <div class="d-flex flex-column min-vh-100">
        <?php include('includes/header.php'); ?>

        <div class="main-content flex-grow-1">
            <div class="row pad-botm mb-4">
                <div class="col-md-12">
                    <h5 class="header-line" style="color:#0d6efd;">MANAGE IN/OUT RECORDS</h5>
                </div>
            </div>

            <!-- Flash Messages -->

            <div class="row justify-content-center">
                <div class="col-md-8" id="flash-container">
                    <?php
                    foreach (['error', 'msg', 'updatemsg', 'delmsg'] as $type):
                        if (!empty($_SESSION[$type])): ?>
                            <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                                <strong><?php echo ucfirst($type); ?> :</strong> <?php echo htmlentities($_SESSION[$type]); ?>
                            </div>
                            <?php $_SESSION[$type] = ""; ?>
                            <?php
                        endif;
                    endforeach;
                    ?>
                </div>
            </div>

            <!-- Date Range Filter Form -->
            <div class="row mb-3">
                <div class="col-md-12">
                    <form method="get" class="d-flex align-items-center flex-wrap gap-2">
                        <div class="d-flex align-items-center gap-1">
                            <label for="from" class="mb-0">From:</label>
                            <input type="date" id="from" name="from" class="form-control form-control-sm"
                                value="<?php echo htmlentities($fromDate); ?>">
                        </div>
                        <div class="d-flex align-items-center gap-1">
                            <label for="to" class="mb-0">To:</label>
                            <input type="date" id="to" name="to" class="form-control form-control-sm"
                                value="<?php echo htmlentities($toDate); ?>">
                        </div>
                        <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-filter"></i>
                            Filter</button>
                        <a href="manage-inout-records.php" class="btn btn-secondary btn-sm"><i
                                class="fa fa-rotate-left"></i> Reset</a>
                    </form>
                </div>
            </div>


            <!-- In/Out Table -->
            <div class="card square-card mb-5">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <div><i class="fa fa-book mr-2"></i> In/Out Records List</div>
                    <button class="btn btn-light btn-sm text-dark shadow-sm rounded-pill px-3"
                        onclick="openInoutModal()">
                        <i class="fa fa-plus-circle"></i><b> ADD</b>
                    </button>
                </div>
                <div class="card-body table-wrapper">
                    <table id="inoutTable" class="table table-bordered table-hover table-sm text-dark">
                        <thead class="table-theme-header">
                            <tr>
                                <th>#</th>
                                <th>Type</th>
                                <th>Name</th>
                                <th>Department</th>
                                <th>Degree</th>
                                <th>Year</th>
                                <th>In Time</th>
                                <th>Out Time</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
$cnt = 1;
foreach ($results as $result) {
?>
<tr>
    <td><?php echo htmlentities($cnt++); ?></td>

    <td>
        <?php
        if ($result->type == 'student') {
            echo '<span class="badge bg-success">Student</span>';
            $sql = "SELECT 
                        s.FullName,
                        dept.department_name,
                        deg.degree_name,
                        s.passed_out_year AS student_year
                    FROM tblstudents s
                    LEFT JOIN tbldepartment dept ON dept.department_id = s.department_id
                    LEFT JOIN tbldegree deg ON deg.degree_id = s.degree_id
                    WHERE s.id = :id";
        } else {
            echo '<span class="badge bg-primary">Staff</span>';
            $sql = "SELECT 
                        s.FullName,
                        dept.department_name
                    FROM tblstaff s
                    LEFT JOIN tbldepartment dept ON dept.department_id = s.department_id
                    WHERE s.id = :id";
        }
        ?>

    </td>

    <?php
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':id', $result->member_id, PDO::PARAM_STR);
    $stmt->execute();
    $info = $stmt->fetch(PDO::FETCH_OBJ);
    ?>

    <td><?= htmlentities($info->FullName ?? '-') ?></td>
    <td><?= htmlentities($info->department_name ?? '-') ?></td>
    <td><?= htmlentities($info->degree_name ?? '-') ?></td>

<td>
    <?php
    if ($result->type == 'student') {

        // Default
        $yearText = "-";

        // Check if student_year contains something like "2024 - 2027"
        if (!empty($info->student_year) && strpos($info->student_year, '-') !== false) {

            $years = explode('-', $info->student_year);
            $passedOutYear = intval(trim($years[1] ?? 0));
            $current = intval(date('Y'));

            $diff = $passedOutYear - $current;

            if ($diff == 3) {
                $yearText = "I";
            } elseif ($diff == 2) {
                $yearText = "II";
            } elseif ($diff == 1) {
                $yearText = "III";
            } else {
                $yearText = "Completed";
            }
        }

        echo $yearText;

    } else {
        echo '-';
    }
    ?>
</td>



    <td><?= $result->in_time ? date("j-n-Y | g:i A", strtotime($result->in_time)) : "-" ?></td>
    <td><?= $result->out_time ? date("j-n-Y | g:i A", strtotime($result->out_time)) : "-" ?></td>

    <td>
        <?php if ($result->out_time == '0000-00-00 00:00:00' || $result->out_time == null): ?>
            <a href="manage-inout-records.php?updateout=<?= htmlentities($result->id) ?>"
                class="btn btn-sm btn-warning"
                onclick="return confirm('Update out time to current time?');">
                <i class="fa fa-clock"></i> Update Out Time
            </a>
        <?php else: ?>
            <span class="badge bg-success">Completed</span>
        <?php endif; ?>
    </td>
</tr>
<?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>

    <!-- In/Out Modal -->
    <div class="modal fade" id="inoutModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered modal-md">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">Add In/Out</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="inoutForm">
                        <div class="form-group">
                            <label>Type</label>
                            <select id="staff_student" name="staff_student" class="form-control" required>
                                <option value="">-- Select --</option>
                                <option value="Staff">Staff</option>
                                <option value="Student">Student</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Select Name</label>
                            <select id="member_id" name="member_id" class="form-control" required>
                                <option value="">-- Select --</option>
                            </select>
                        </div>

                </div>
                <div class="modal-footer justify-content-center py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal"><i
                            class="fa fa-times"></i> Cancel</button>
                    <button type="submit" id="saveBtn" class="btn btn-success btn-sm"><i class="fa fa-save"></i>
                        Save</button>
                </div>
                </form>
            </div>
        </div>
    </div>

    <?php include('includes/footer.php'); ?>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        $(document).ready(function () {
            $('#inoutTable').DataTable({ pageLength: 10, responsive: true, language: { search: "🔍 Search records:" } });

            function openInoutModal() {
                $('#staff_student').val('').trigger('change');
                $('#member_id').empty().append('<option value="">-- Select --</option>');
                $('#inoutModal').modal('show');
            }
            window.openInoutModal = openInoutModal;

            $('#staff_student').change(function () {
                var type = $(this).val();
                $('#member_id').val(null).trigger('change');
                if (type) {
                    $('#member_id').select2({
                        placeholder: 'Search ' + type,
                        ajax: {
                            url: 'get_staff_student_list.php',
                            dataType: 'json',
                            delay: 250,
                            data: params => ({ q: params.term, type: type }),
                            processResults: data => ({ results: data.map(item => ({ id: item.studentID, text: item.BorrowerID + ' - ' + item.FullName })) })
                        },
                        dropdownParent: $('#inoutModal')
                    });
                }
            });

            $('#inoutForm').on('submit', function (e) {
                e.preventDefault();
                var type = $('#staff_student').val();
                var member_id = $('#member_id').val();
                if (!type || !member_id) { alert("Please select type and name"); return; }
                $.post('save-inout.php', { type: type, member_id: member_id }, function () { location.reload(); });
            });
        });
    </script>
</body>

</html>