<?php
require_once __DIR__ . '/../../core/helpers.php';
// Kiểm tra session và quyền
if (session_status() == PHP_SESSION_NONE) session_start();
if (!has_permission('attendance')) { header("Location: /quanlybanhang/403.php"); exit; }

require_once __DIR__ . '/../../templates/header.php';

// Xử lý Lọc dữ liệu
$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : date('Y-m-01');
$to_date = isset($_GET['to_date']) ? $_GET['to_date'] : date('Y-m-d');
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

// Truy vấn danh sách nhân viên để nạp vào Select Box
$sql_users = "SELECT id, display_name FROM cms_users WHERE user_status = 1";
$users = $conn->query($sql_users)->fetch_all(MYSQLI_ASSOC);

// Truy vấn dữ liệu chấm công
$sql = "SELECT a.*, u.display_name, u.user_code 
        FROM cms_attendance a 
        LEFT JOIN cms_users u ON a.user_id = u.id 
        WHERE a.work_date BETWEEN '$from_date' AND '$to_date'";

if ($user_id > 0) {
    $sql .= " AND a.user_id = $user_id";
}
$sql .= " ORDER BY a.work_date DESC, a.check_in DESC";
$result = $conn->query($sql);
?>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 text-gray-800">Quản lý Chấm công</h1>
        <div>
             <a href="qr_list.php" class="btn btn-info btn-sm shadow-sm"><i class="fas fa-qrcode fa-sm text-white-50"></i> Danh sách QR Code</a>
             <a href="#" class="btn btn-primary btn-sm shadow-sm" data-toggle="modal" data-target="#modalManualCheck"><i class="fas fa-plus fa-sm text-white-50"></i> Chấm công thủ công</a>
        </div>
    </div>

    <div class="card shadow mb-4 border-left-primary">
        <div class="card-body">
            <form method="GET" class="row align-items-end">
                <div class="col-md-3">
                    <label>Từ ngày</label>
                    <input type="date" name="from_date" class="form-control" value="<?php echo $from_date; ?>">
                </div>
                <div class="col-md-3">
                    <label>Đến ngày</label>
                    <input type="date" name="to_date" class="form-control" value="<?php echo $to_date; ?>">
                </div>
                <div class="col-md-3">
                    <label>Nhân viên</label>
                    <select name="user_id" class="form-control">
                        <option value="0">Tất cả nhân viên</option>
                        <?php foreach($users as $u): ?>
                            <option value="<?php echo $u['id']; ?>" <?php echo ($user_id == $u['id']) ? 'selected' : ''; ?>>
                                <?php echo $u['display_name']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary btn-block"><i class="fas fa-search"></i> Tìm kiếm</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Danh sách ngày công</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                    <thead class="thead-light">
                        <tr>
                            <th>Nhân viên</th>
                            <th>Ngày làm</th>
                            <th class="text-center">Giờ vào (In)</th>
                            <th class="text-center">Giờ ra (Out)</th>
                            <th class="text-center">Tổng giờ</th>
                            <th class="text-center">Trạng thái</th>
                            <th class="text-center">Hành động</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($result->num_rows > 0): ?>
                            <?php while($row = $result->fetch_assoc()): 
                                $in = $row['check_in'] ? date('H:i', strtotime($row['check_in'])) : '--:--';
                                $out = $row['check_out'] ? date('H:i', strtotime($row['check_out'])) : '--:--';
                                
                                // Tính tổng giờ
                                $total_hours = 0;
                                if($row['check_in'] && $row['check_out']){
                                    $diff = strtotime($row['check_out']) - strtotime($row['check_in']);
                                    $total_hours = round($diff / 3600, 1);
                                }
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo $row['display_name']; ?></strong><br>
                                    <small class="text-muted"><?php echo $row['user_code']; ?></small>
                                </td>
                                <td><?php echo date('d/m/Y', strtotime($row['work_date'])); ?></td>
                                <td class="text-center text-success font-weight-bold"><?php echo $in; ?></td>
                                <td class="text-center text-danger font-weight-bold"><?php echo $out; ?></td>
                                <td class="text-center">
                                    <?php if($total_hours > 0) echo $total_hours . ' h'; else echo '-'; ?>
                                </td>
                                <td class="text-center">
                                    <?php if($row['status'] == 1): ?>
                                        <span class="badge badge-warning">Đang làm việc</span>
                                    <?php else: ?>
                                        <span class="badge badge-success">Hoàn thành</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <button class="btn btn-sm btn-info edit-btn" data-id="<?php echo $row['id']; ?>"><i class="fas fa-edit"></i></button>
                                    <button class="btn btn-sm btn-danger delete-btn" data-id="<?php echo $row['id']; ?>"><i class="fas fa-trash"></i></button>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="7" class="text-center">Không có dữ liệu chấm công nào.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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