<?php
$page_title = 'Daftar Karyawan Harian';
require_once('includes/load.php');
page_require_level(4);

// --- PERBAIKAN: Menggunakan getInstance() untuk mendapatkan koneksi DB ---
$db = MySqli_DB::getInstance();

// --- Ekspor ke Excel ---
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['export_excel'])) {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="daily_employee_data.xls"');
    header('Cache-Control: max-age=0');

    // Build the SQL query for export
    $sql = "SELECT id, first_name, last_name, email, phone_number, hire_date, job_title, status, kontak_darurat
            FROM employees_harian";

    // Handle search and filter parameters for export
    $search_term = isset($_GET['search']) ? $db->escape($_GET['search']) : '';
    $status = isset($_GET['status']) ? $db->escape($_GET['status']) : '';

    $where_clauses = [];
    if (!empty($search_term)) {
        $where_clauses[] = " (first_name LIKE '%{$search_term}%' OR last_name LIKE '%{$search_term}%' OR id LIKE '%{$search_term}%') ";
    }
    if (!empty($status)) {
        $where_clauses[] = " status = '{$status}' ";
    }

    if (!empty($where_clauses)) {
        $sql .= " WHERE " . implode(' AND ', $where_clauses);
    }
    
    $result = $db->query($sql);

    // Generate table for export
    echo '<table border="1">';
    echo '<thead><tr><th>#</th><th>Nama Lengkap</th><th>Email</th><th>Nomor Telepon</th><th>Jabatan</th><th>Tanggal Masuk</th><th>Status</th><th>Kontak Darurat</th></tr></thead>';
    echo '<tbody>';
    $i = 1;
    while ($row = $db->fetch_assoc($result)) {
        echo '<tr>';
        echo '<td>' . $i++ . '</td>';
        echo '<td>' . htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) . '</td>';
        echo '<td>' . htmlspecialchars($row['email']) . '</td>';
        echo '<td>' . htmlspecialchars($row['phone_number']) . '</td>';
        echo '<td>' . htmlspecialchars($row['job_title']) . '</td>';
        echo '<td>' . htmlspecialchars($row['hire_date']) . '</td>';
        echo '<td>' . htmlspecialchars($row['status']) . '</td>';
        echo '<td>' . htmlspecialchars($row['kontak_darurat']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody>';
    echo '</table>';

    exit;
}

// --- Metrik Dashboard ---
$total_employees_count = find_by_sql("SELECT COUNT(*) AS total FROM employees_harian")[0]['total'];
$active_employees_count = find_by_sql("SELECT COUNT(*) AS total FROM employees_harian WHERE status = 'Active'")[0]['total'];
$on_leave_employees_count = find_by_sql("SELECT COUNT(*) AS total FROM employees_harian WHERE status = 'On Leave'")[0]['total'];

// --- Paginasi, Pencarian, dan Filter ---
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 10;
$search_term = isset($_GET['search']) ? $db->escape($_GET['search']) : '';
$status = isset($_GET['status']) ? $db->escape($_GET['status']) : '';

// Query untuk menghitung total baris
$sql_count = "SELECT COUNT(*) AS total FROM employees_harian";
$where_clauses = [];
if (!empty($search_term)) {
    $where_clauses[] = " (first_name LIKE '%{$search_term}%' OR last_name LIKE '%{$search_term}%' OR id LIKE '%{$search_term}%') ";
}
if (!empty($status)) {
    $where_clauses[] = " status = '{$status}' ";
}
if (!empty($where_clauses)) {
    $sql_count .= " WHERE " . implode(' AND ', $where_clauses);
}

$result_count = $db->query($sql_count);
$total_employees_filtered = $db->fetch_assoc($result_count)['total'];
$total_pages = ceil($total_employees_filtered / $per_page);
$start = ($page - 1) * $per_page;

// Query utama untuk menampilkan data
$sql = "SELECT id, first_name, last_name, email, phone_number, hire_date, job_title, status, kontak_darurat
        FROM employees_harian";

if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}
$sql .= " LIMIT {$per_page} OFFSET {$start}";
$employees = find_by_sql($sql);
?>

<?php include_once('layouts/header.php'); ?>

<style>
    .dashboard-panel {
        display: flex;
        justify-content: space-around;
        flex-wrap: wrap;
    }
    .dashboard-panel .col-md-4 {
        flex: 1 1 30%;
        margin-bottom: 20px;
    }
    .panel-heading i {
        margin-right: 5px;
    }
    .btn-group .btn {
        margin-right: 2px;
    }
</style>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row dashboard-panel">
    <div class="col-md-4">
        <div class="panel panel-info">
            <div class="panel-heading">
                <i class="glyphicon glyphicon-user"></i> Total Karyawan Harian
            </div>
            <div class="panel-body text-center">
                <h2><?php echo number_format($total_employees_count); ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="panel panel-success">
            <div class="panel-heading">
                <i class="glyphicon glyphicon-ok-circle"></i> Karyawan Aktif
            </div>
            <div class="panel-body text-center">
                <h2><?php echo number_format($active_employees_count); ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="panel panel-danger">
            <div class="panel-heading">
                <i class="glyphicon glyphicon-time"></i> Karyawan Cuti
            </div>
            <div class="panel-body text-center">
                <h2><?php echo number_format($on_leave_employees_count); ?></h2>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    <span>Daftar Karyawan Harian</span>
                </strong>
                <a href="add_employee_harian.php" class="btn btn-info pull-right">Tambah Karyawan Harian</a>
            </div>
            <div class="panel-body">
                <form action="" method="GET" class="form-horizontal mb-4">
                    <div class="form-group clearfix">
                        <div class="col-md-4">
                            <input type="text" name="search" class="form-control" placeholder="Cari nama atau ID..." value="<?php echo htmlspecialchars($search_term); ?>">
                        </div>
                        <div class="col-md-4">
                            <select name="status" class="form-control">
                                <option value="">Semua Status</option>
                                <option value="Active" <?php if ($status == 'Active') echo 'selected'; ?>>Aktif</option>
                                <option value="On Leave" <?php if ($status == 'On Leave') echo 'selected'; ?>>Cuti</option>
                                <option value="Terminated" <?php if ($status == 'Terminated') echo 'selected'; ?>>Keluar</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <select name="per_page" class="form-control">
                                <option value="10" <?php if ($per_page == 10) echo 'selected'; ?>>10 per halaman</option>
                                <option value="25" <?php if ($per_page == 25) echo 'selected'; ?>>25 per halaman</option>
                                <option value="50" <?php if ($per_page == 50) echo 'selected'; ?>>50 per halaman</option>
                                <option value="100" <?php if ($per_page == 100) echo 'selected'; ?>>100 per halaman</option>
                            </select>
                        </div>
                        <div class="col-md-12 text-right mt-3">
                             <button type="submit" class="btn btn-primary">Filter</button>
                             <a href="employees_harian.php" class="btn btn-default">Reset</a>
                             <a href="?export_excel=1&search=<?php echo urlencode($search_term); ?>&status=<?php echo urlencode($status); ?>" class="btn btn-success">Export Excel</a>
                        </div>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th class="text-center" style="width: 50px;">#</th>
                                <th>Nama Lengkap</th>
                                <th class="text-center">Jabatan</th>
                                <th class="text-center">Tanggal Masuk</th>
                                <th class="text-center">Status</th>
                                <th class="text-center">Kontak Darurat</th>
                                <th class="text-center" style="width: 100px;">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($employees)): ?>
                                <?php $i = $start + 1; ?>
                                <?php foreach ($employees as $employee) : ?>
                                    <tr>
                                        <td class="text-center"><?php echo (int)$i++; ?></td>
                                        <td><?php echo remove_junk($employee['first_name']) . ' ' . remove_junk($employee['last_name']); ?></td>
                                        <td class="text-center"><?php echo remove_junk($employee['job_title']); ?></td>
                                        <td class="text-center"><?php echo htmlspecialchars($employee['hire_date']); ?></td>
                                        <td class="text-center">
                                            <?php if ($employee['status'] == 'Active'): ?>
                                                <span class="label label-success"><?php echo htmlspecialchars($employee['status']); ?></span>
                                            <?php elseif ($employee['status'] == 'On Leave'): ?>
                                                <span class="label label-warning"><?php echo htmlspecialchars($employee['status']); ?></span>
                                            <?php else: ?>
                                                <span class="label label-danger"><?php echo htmlspecialchars($employee['status']); ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center"><?php echo htmlspecialchars($employee['kontak_darurat']); ?></td>
                                        <td class="text-center">
                                            <div class="btn-group">
                                                <a href="edit_employee_harian.php?id=<?php echo (int)$employee['id'];?>" class="btn btn-xs btn-warning" title="Edit" data-toggle="tooltip">
                                                    <i class="glyphicon glyphicon-pencil"></i>
                                                </a>
                                                <a href="delete_employee_harian.php?id=<?php echo (int)$employee['id'];?>" class="btn btn-xs btn-danger" title="Hapus" data-toggle="tooltip" onclick="return confirm('Apakah Anda yakin ingin menghapus karyawan ini?');">
                                                    <i class="glyphicon glyphicon-remove"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="text-center">Tidak ada data karyawan harian ditemukan.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($total_pages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination pull-right">
                            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                <a class="page-link" href="?page=<?php echo $page - 1; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>&status=<?php echo urlencode($status); ?>">Prev</a>
                            </li>
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php if ($i == $page) echo 'active'; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>&status=<?php echo urlencode($status); ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                <a class="page-link" href="?page=<?php echo $page + 1; ?>&per_page=<?php echo $per_page; ?>&search=<?php echo urlencode($search_term); ?>&status=<?php echo urlencode($status); ?>">Next</a>
                            </li>
                        </ul>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>