<?php $pdo = $db; ?>
<?php
if (!is_admin()) {
    // header('Location: index.php'); exit;
}

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

$where = "1=1";
$params = [];

if (!empty($_GET['employee_id'])) {
    $where .= " AND a.employee_id = ?";
    $params[] = $_GET['employee_id'];
}
if (!empty($_GET['date'])) {
    $where .= " AND a.date = ?";
    $params[] = $_GET['date'];
}

$logs = $pdo->prepare("
    SELECT a.*, e.name_en, e.name_ar 
    FROM attendance_logs a 
    JOIN employees e ON a.employee_id = e.id 
    WHERE $where
    ORDER BY a.date DESC, a.check_in DESC 
    LIMIT $limit OFFSET $offset
");
$logs->execute($params);
$logs = $logs->fetchAll(PDO::FETCH_ASSOC);

$total_logs = $pdo->prepare("SELECT COUNT(*) FROM attendance_logs a WHERE $where");
$total_logs->execute($params);
$total_rows = $total_logs->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$employees = $pdo->query("SELECT id, name_en FROM employees ORDER BY name_en")->fetchAll(PDO::FETCH_KEY_PAIR);

// Handle Manual Add
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_attendance'])) {
    $emp_id = $_POST['employee_id'];
    $date = $_POST['date'];
    $check_in = $_POST['check_in'] ? "$date " . $_POST['check_in'] : null;
    $check_out = $_POST['check_out'] ? "$date " . $_POST['check_out'] : null;
    $status = $_POST['status'];

    $stmt = $pdo->prepare("INSERT INTO attendance_logs (employee_id, date, check_in, check_out, status, source) VALUES (?, ?, ?, ?, ?, 'Manual')");
    $stmt->execute([$emp_id, $date, $check_in, $check_out, $status]);
    
    echo "<script>window.location.href='hr_attendance.php';</script>";
}
?>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800"><?php echo __("attendance_logs"); ?></h1>
        <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addAttendanceModal">
            <i class="fas fa-plus"></i> <?php echo __("manual_entry"); ?>
        </button>
    </div>

    <!-- Filter -->
    <div class="card shadow mb-4">
        <div class="card-body">
            <form method="GET" class="form-inline">
                <select name="employee_id" class="form-control mr-2 mb-2">
                    <option value=""><?php echo __("all_employees"); ?></option>
                    <?php foreach ($employees as $id => $name): ?>
                        <option value="<?php echo $id; ?>" <?php echo (isset($_GET['employee_id']) && $_GET['employee_id'] == $id) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <input type="date" name="date" class="form-control mr-2 mb-2" value="<?php echo $_GET['date'] ?? ''; ?>">
                <button type="submit" class="btn btn-primary mb-2"><?php echo __("filter"); ?></button>
            </form>
        </div>
    </div>

    <!-- Table -->
    <div class="card shadow mb-4">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th><?php echo __("id"); ?></th>
                            <th><?php echo __("employee"); ?></th>
                            <th><?php echo __("date"); ?></th>
                            <th><?php echo __("check_in"); ?></th>
                            <th><?php echo __("check_out"); ?></th>
                            <th><?php echo __("status"); ?></th>
                            <th><?php echo __("source"); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logs as $log): ?>
                        <tr>
                            <td><?php echo $log['id']; ?></td>
                            <td><?php echo htmlspecialchars($log['name_en']); ?></td>
                            <td><?php echo $log['date']; ?></td>
                            <td><?php echo $log['check_in'] ? date('H:i', strtotime($log['check_in'])) : '-'; ?></td>
                            <td><?php echo $log['check_out'] ? date('H:i', strtotime($log['check_out'])) : '-'; ?></td>
                            <td>
                                <span class="badge badge-<?php 
                                    echo $log['status'] == 'Present' ? 'success' : 
                                        ($log['status'] == 'Late' ? 'warning' : 'danger'); 
                                ?>">
                                    <?php echo $log['status']; ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($log['source']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($logs)): ?>
                        <tr><td colspan="7" class="text-center"><?php echo __("no_logs_found"); ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>&employee_id=<?php echo $_GET['employee_id'] ?? ''; ?>&date=<?php echo $_GET['date'] ?? ''; ?>">
                                <?php echo $i; ?>
                            </a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addAttendanceModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <form method="POST">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo __("add_attendance_log"); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="add_attendance" value="1">
                    <div class="form-group">
                        <label><?php echo __("employee"); ?></label>
                        <select name="employee_id" class="form-control" required>
                            <?php foreach ($employees as $id => $name): ?>
                                <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($name); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label><?php echo __("date"); ?></label>
                        <input type="date" name="date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="form-group row">
                        <div class="col-6">
                            <label><?php echo __("check_in_time"); ?></label>
                            <input type="time" name="check_in" class="form-control">
                        </div>
                        <div class="col-6">
                            <label><?php echo __("check_out_time"); ?></label>
                            <input type="time" name="check_out" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label><?php echo __("status"); ?></label>
                        <select name="status" class="form-control">
                            <option value="Present"><?php echo __("present"); ?></option>
                            <option value="Late"><?php echo __("late"); ?></option>
                            <option value="Absent"><?php echo __("absent"); ?></option>
                            <option value="On Leave"><?php echo __("on_leave"); ?></option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo __("close"); ?></button>
                    <button type="submit" class="btn btn-primary"><?php echo __("save"); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>
