<?php
require_once 'includes/db.php';
require_once 'includes/auth.php';

$company_id = $_SESSION['company_id'];
$user_id = $_SESSION['user_id'];
$is_mgr = hasRole(['owner', 'manager']);
$is_owner = hasRole('owner');

// Fetch user's employee details and shift working hours
$me = fetch("
    SELECT e.id, e.name, e.reporting_manager_id, s.working_hours 
    FROM employees e 
    LEFT JOIN shifts s ON e.shift_id = s.id 
    WHERE e.user_id = ? AND e.company_id = ?
", [$user_id, $company_id]);
$my_id = $me ? $me['id'] : null;

$std_working_hours = ($me && $me['working_hours'] !== null) ? (float)$me['working_hours'] : 8.00;

// Fetch my reporting manager name
$my_mgr_name = 'Not Assigned';
if ($me && $me['reporting_manager_id']) {
    $my_mgr_name = fetchValue("SELECT name FROM users WHERE id = ?", [$me['reporting_manager_id']]) ?: 'Not Assigned';
}

// Fetch my overtime requests
$my_requests = [];
if ($my_id) {
    $my_requests = fetchAll("
        SELECT r.*, m.name as manager_name 
        FROM overtime_requests r
        LEFT JOIN users m ON r.reporting_manager_id = m.id
        WHERE r.employee_id = ? AND r.company_id = ?
        ORDER BY r.date DESC, r.created_at DESC
    ", [$my_id, $company_id]);
}

// Fetch requests assigned to me for approval
$assigned_requests = [];
if ($is_mgr) {
    if ($is_owner) {
        // Owner sees all
        $assigned_requests = fetchAll("
            SELECT r.*, e.name as employee_name, m.name as manager_name
            FROM overtime_requests r
            JOIN employees e ON r.employee_id = e.id
            LEFT JOIN users m ON r.reporting_manager_id = m.id
            WHERE r.company_id = ?
            ORDER BY r.date DESC, r.created_at DESC
        ", [$company_id]);
    } else {
        // Manager sees only those assigned to them
        $assigned_requests = fetchAll("
            SELECT r.*, e.name as employee_name
            FROM overtime_requests r
            JOIN employees e ON r.employee_id = e.id
            WHERE r.company_id = ? AND r.reporting_manager_id = ?
            ORDER BY r.date DESC, r.created_at DESC
        ", [$company_id, $user_id]);
    }
}

// Separate pending and completed requests in approvals queue
$pending_approvals = [];
$past_approvals = [];
foreach ($assigned_requests as $req) {
    if ($req['status'] === 'pending') {
        $pending_approvals[] = $req;
    } else {
        $past_approvals[] = $req;
    }
}

// Fetch all employees for manual logging
$employees = [];
if ($is_mgr) {
    $employees = fetchAll("SELECT id, name FROM employees WHERE company_id = ? ORDER BY name ASC", [$company_id]);
}

// Fetch user's recent 30-day logs
$my_logs = [];
if ($my_id) {
    $my_logs = fetchAll("
        SELECT * FROM attendance 
        WHERE employee_id = ? AND company_id = ? 
        ORDER BY date DESC, clock_in DESC 
        LIMIT 30
    ", [$my_id, $company_id]);
}

// Fetch all logs for managers
$all_logs = [];
if ($is_mgr) {
    $all_logs = fetchAll("
        SELECT a.*, e.name as employee_name 
        FROM attendance a
        JOIN employees e ON a.employee_id = e.id
        WHERE a.company_id = ? 
        ORDER BY a.date DESC, a.clock_in DESC 
        LIMIT 100
    ", [$company_id]);
}
?>



<!-- Tabs -->
<div class="tabs-container" style="margin-bottom: 1.5rem;">
    <div style="display: flex; gap: 0.5rem; border-bottom: 1px solid var(--border); padding-bottom: 0.5rem;">
        <?php if (!$is_owner): ?>
        <button class="btn tab-btn active" onclick="switchTab('my-clock-tab', this)">
            <i class="fas fa-clock" style="margin-right: 0.5rem;"></i>My Logs
        </button>
        <?php endif; ?>
        <?php if (!$is_owner): ?>
        <button class="btn tab-btn" onclick="switchTab('my-overtime-tab', this)">
            <i class="fas fa-clock-rotate-left" style="margin-right: 0.5rem;"></i>My Overtime Logs
        </button>
        <?php endif; ?>
        <?php if ($is_mgr): ?>
        <button class="btn tab-btn <?php echo $is_owner ? 'active' : ''; ?>" onclick="switchTab('all-logs-tab', this)">
            <i class="fas fa-list-check" style="margin-right: 0.5rem;"></i>Company Attendance Logs
        </button>
        <?php endif; ?>
        <?php if ($is_mgr): ?>
        <button class="btn tab-btn" onclick="switchTab('approvals-tab', this)">
            <i class="fas fa-business-time" style="margin-right: 0.5rem;"></i>Approvals
            <?php 
            $pending_ot_count = count($pending_approvals);
            if ($pending_ot_count > 0):
            ?>
            <span style="background: var(--danger); color: white; border-radius: 50%; padding: 0.1rem 0.4rem; font-size: 0.7rem; font-weight: 700; margin-left: 0.25rem;"><?php echo $pending_ot_count; ?></span>
            <?php endif; ?>
        </button>
        <?php endif; ?>
    </div>
</div>

<!-- TAB 1: MY LOGS -->
<?php if (!$is_owner): ?>
<div id="my-clock-tab" class="tab-content active-content">
    <div style="display: grid; grid-template-columns: 1fr; gap: 1.5rem; align-items: start;">
        
        <!-- Personal Logs Table -->
        <div class="card" style="padding: 1.5rem;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; flex-wrap: wrap; gap: 1rem;">
                <h3 style="margin: 0; font-size: 1.1rem; display: flex; align-items: center; gap: 0.5rem;">
                    <i class="fas fa-history" style="color: var(--primary); integrity: inherit;"></i> My Recent Clock Logs
                </h3>
                
                <div style="display: flex; gap: 0.5rem; align-items: center;">
                    <input type="date" id="my_logs_start" class="form-control" style="padding: 0.35rem 0.5rem; font-size: 0.85rem; width: 140px;" onchange="loadMyLogs()">
                    <span style="color: var(--text-muted); font-size: 0.85rem;">to</span>
                    <input type="date" id="my_logs_end" class="form-control" style="padding: 0.35rem 0.5rem; font-size: 0.85rem; width: 140px;" onchange="loadMyLogs()">
                </div>
            </div>
            
            <div class="table-container" style="overflow-x: auto;">
                <table class="table" style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="border-bottom: 2px solid var(--border); text-align: left;">
                            <th style="padding: 0.75rem 0.5rem;">Clock In</th>
                            <th style="padding: 0.75rem 0.5rem;">Clock Out</th>
                            <th style="padding: 0.75rem 0.5rem;">Status</th>
                            <th style="padding: 0.75rem 0.5rem;">Source</th>
                            <th style="padding: 0.75rem 0.5rem;">Hours Worked</th>
                        </tr>
                    </thead>
                    <tbody id="myLogsTableBody">
                        <tr>
                            <td colspan="5" style="text-align: center; color: var(--text-muted); padding: 2rem;">Loading clock logs...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>
<?php endif; ?>

<!-- TAB 2: ALL LOGS (MANAGER ONLY) -->
<?php if ($is_mgr): ?>
<div id="all-logs-tab" class="tab-content" style="<?php echo $is_owner ? 'display: block;' : 'display: none;'; ?>">
    <div class="card" style="padding: 1.5rem; margin-bottom: 1.5rem;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
            <h3 style="margin: 0; font-size: 1.1rem;"><i class="fas fa-clock-rotate-left" style="color: var(--primary); margin-right: 0.5rem;"></i> All Attendance Records</h3>
            <div style="display: flex; gap: 0.5rem;">
                <a href="attendance-kiosk" target="_blank" class="btn" style="background: var(--success); color: white; display: inline-flex; align-items: center; gap: 0.35rem; text-decoration: none;">
                    <i class="fas fa-qrcode"></i> Open QR Kiosk
                </a>
                <button class="btn" style="background: var(--primary); color: white;" onclick="openAddManualLogModal()">
                    <i class="fas fa-plus" style="margin-right: 0.5rem;"></i>Add Manual Log
                </button>
            </div>
        </div>

        <!-- Filters -->
        <div style="display: flex; gap: 0.75rem; margin-bottom: 1.25rem; align-items: center; flex-wrap: wrap;">
            <div style="display: flex; gap: 0.5rem; align-items: center; flex-grow: 1; max-width: 300px;">
                <input type="text" id="all_logs_search" class="form-control" placeholder="Search by name or employee ID..." style="padding: 0.35rem 0.75rem; font-size: 0.85rem;" oninput="filterAllLogs()">
            </div>
            <div style="display: flex; gap: 0.5rem; align-items: center;">
                <input type="date" id="all_logs_start" class="form-control" style="padding: 0.35rem 0.5rem; font-size: 0.85rem; width: 140px;" onchange="loadAllLogs()">
                <span style="color: var(--text-muted); font-size: 0.85rem;">to</span>
                <input type="date" id="all_logs_end" class="form-control" style="padding: 0.35rem 0.5rem; font-size: 0.85rem; width: 140px;" onchange="loadAllLogs()">
            </div>
            <div style="display: flex; gap: 0.5rem; align-items: center;">
                <select id="all_logs_status" class="form-control" style="padding: 0.35rem 0.5rem; font-size: 0.85rem; width: 130px;" onchange="filterAllLogs()">
                    <option value="all">All Statuses</option>
                    <option value="present">Present</option>
                    <option value="late">Late</option>
                    <option value="absent">Absent</option>
                    <option value="half_day">Half Day</option>
                    <option value="short_leave">Short Leave</option>
                </select>
            </div>
        </div>
        
        <div class="table-container" style="overflow-x: auto;">
            <table class="table" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="border-bottom: 2px solid var(--border); text-align: left;">
                        <th style="padding: 0.75rem 0.5rem;">Date</th>
                        <th style="padding: 0.75rem 0.5rem;">Clock In</th>
                        <th style="padding: 0.75rem 0.5rem;">Clock Out</th>
                        <th style="padding: 0.75rem 0.5rem;">Status</th>
                        <th style="padding: 0.75rem 0.5rem;">Source</th>
                        <th style="padding: 0.75rem 0.5rem;">Hours Worked</th>
                        <th style="padding: 0.75rem 0.5rem; text-align: right;">Actions</th>
                    </tr>
                </thead>
                <tbody id="allLogsTableBody">
                    <tr>
                        <td colspan="7" style="text-align: center; color: var(--text-muted); padding: 2rem;">Loading attendance records...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Manual Attendance Modal -->
<div id="manualLogModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h2 id="modalTitle" style="margin: 0; font-size: 1.25rem;">Add Manual Clock Log</h2>
            <button class="btn btn-icon" onclick="closeModal('manualLogModal')"><i class="fas fa-times"></i></button>
        </div>
        <form id="manualLogForm" onsubmit="saveManualLog(event)">
            <input type="hidden" id="log_id" name="id">
            
            <div class="modal-body">
                <div class="form-group" style="position: relative;">
                    <label class="form-label">Employee <span class="required-mark">*</span></label>
                    <input type="text" id="employee_search_input" class="form-control" placeholder="Search employee by name..." autocomplete="off" required>
                    <input type="hidden" id="log_employee_id" name="employee_id" required>
                    <div id="employee_suggestions" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: var(--bg-card); border: 1px solid var(--border); border-radius: 10px; max-height: 180px; overflow-y: auto; z-index: 1050; margin-top: 5px; box-shadow: 0 4px 20px rgba(0,0,0,0.15);"></div>
                </div>

                <div class="form-group">
                    <label class="form-label">Date <span class="required-mark">*</span></label>
                    <input type="date" id="log_date" name="date" class="form-control" value="<?php echo date('Y-m-d'); ?>" readonly required>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Clock In Time <span class="required-mark">*</span></label>
                        <input type="time" id="log_clock_in" name="clock_in" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Clock Out Time</label>
                        <input type="time" id="log_clock_out" name="clock_out" class="form-control">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Status <span class="required-mark">*</span></label>
                    <select id="log_status" name="status" class="form-control" required>
                        <option value="present">Present</option>
                        <option value="late">Late</option>
                        <option value="absent">Absent</option>
                        <option value="half_day">Half Day</option>
                        <option value="short_leave">Short Leave</option>
                    </select>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn" style="background: rgba(0,0,0,0.05);" onclick="closeModal('manualLogModal')">Cancel</button>
                <button type="submit" class="btn" style="background: var(--primary); color: white;">Save Log</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- TAB 3: MY OVERTIME LOGS -->
<?php if (!$is_owner): ?>
<div id="my-overtime-tab" class="tab-content" style="display: none;">
    <div style="font-size: 0.85rem; color: var(--text-muted); margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.5rem;">
        <i class="fas fa-info-circle" style="color: var(--primary);"></i>
        <span>Reporting Manager: <strong><?php echo e($my_mgr_name); ?></strong>. Any working hours exceeding <?php echo number_format($std_working_hours, 2); ?> per day automatically submit a request.</span>
    </div>

    <div class="card" style="padding: 1.5rem;">
        <h3 style="margin-top: 0; margin-bottom: 1rem; font-size: 1.1rem;"><i class="fas fa-history" style="color: var(--primary); margin-right: 0.5rem;"></i> My Overtime History</h3>
        
        <div class="table-container" style="overflow-x: auto;">
            <table class="table" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="border-bottom: 2px solid var(--border); text-align: left;">
                        <th style="padding: 0.75rem 0.5rem;">Date</th>
                        <th style="padding: 0.75rem 0.5rem;">Extra Hours</th>
                        <th style="padding: 0.75rem 0.5rem;">Assigned Manager</th>
                        <th style="padding: 0.75rem 0.5rem;">Status</th>
                        <th style="padding: 0.75rem 0.5rem;">Manager Comments</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($my_requests)): ?>
                        <tr>
                            <td colspan="5" style="text-align: center; color: var(--text-muted); padding: 2rem;">No overtime requests logged yet.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($my_requests as $req): ?>
                            <tr style="border-bottom: 1px solid var(--border);">
                                <td style="padding: 0.75rem 0.5rem; font-weight: 600;"><?php echo e($req['date']); ?></td>
                                <td style="padding: 0.75rem 0.5rem; font-weight: 600; color: var(--primary);"><?php echo number_format($req['hours'], 2); ?> Hrs</td>
                                <td style="padding: 0.75rem 0.5rem; color: var(--text-muted);"><?php echo e($req['manager_name'] ?: 'Not Assigned / Company Owner'); ?></td>
                                <td style="padding: 0.75rem 0.5rem;">
                                    <?php
                                    $bg = 'rgba(0,0,0,0.05)';
                                    $fg = 'var(--text-muted)';
                                    if ($req['status'] === 'approved') {
                                        $bg = 'rgba(16, 185, 129, 0.1)';
                                        $fg = '#10B981';
                                    } elseif ($req['status'] === 'rejected') {
                                        $bg = 'rgba(239, 68, 68, 0.1)';
                                        $fg = '#EF4444';
                                    } elseif ($req['status'] === 'pending') {
                                        $bg = 'rgba(245, 158, 11, 0.1)';
                                        $fg = '#F59E0B';
                                    }
                                    ?>
                                    <span class="badge" style="
                                        background: <?php echo $bg; ?>; color: <?php echo $fg; ?>;
                                        padding: 0.25rem 0.5rem; border-radius: 6px; font-size: 0.75rem; text-transform: uppercase; font-weight: 600;
                                    "><?php echo e($req['status']); ?></span>
                                </td>
                                <td style="padding: 0.75rem 0.5rem; font-size: 0.85rem; color: var(--text-muted);">
                                    <?php echo e($req['comments'] ?: '-'); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- TAB 4: OVERTIME APPROVALS (MANAGER ONLY) -->
<?php if ($is_mgr): ?>
<div id="approvals-tab" class="tab-content" style="display: none;">
    <!-- Sub-tab styles -->
    <style>
        .sub-tab-btn {
            background: transparent;
            border: none;
            color: var(--text-muted);
            font-weight: 600;
            padding: 0.75rem 1.25rem;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            font-size: 0.9rem;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
        }
        .sub-tab-btn:hover {
            color: var(--primary);
            background: rgba(99, 102, 241, 0.05);
            border-radius: 8px 8px 0 0;
        }
        .sub-tab-btn.active {
            color: var(--primary);
            border-bottom: 2px solid var(--primary);
        }
    </style>

    <!-- Sub-tab navigation -->
    <div style="display: flex; gap: 0.5rem; margin-bottom: 1.5rem; border-bottom: 1px solid var(--border);">
        <button class="sub-tab-btn active" onclick="switchSubTab('ot-pending-subtab', this)">
            <i class="fas fa-hourglass-half" style="margin-right: 0.5rem;"></i>Pending Approvals
            <?php 
            $pending_ot_count = count($pending_approvals);
            if ($pending_ot_count > 0):
            ?>
            <span id="pendingOTCountBadge" style="background: var(--danger); color: white; border-radius: 50%; padding: 0.1rem 0.4rem; font-size: 0.7rem; font-weight: 700; margin-left: 0.35rem;"><?php echo $pending_ot_count; ?></span>
            <?php endif; ?>
        </button>
        <button class="sub-tab-btn" onclick="switchSubTab('ot-past-subtab', this)">
            <i class="fas fa-circle-check" style="margin-right: 0.5rem;"></i>Past Approvals & Rejections
        </button>
    </div>

    <!-- Unified Filters Card for Overtime Approvals -->
    <div class="card" style="padding: 1.25rem; margin-bottom: 1.5rem; display: flex; gap: 1rem; flex-wrap: wrap; align-items: flex-end; background: var(--bg-card); border: 1px solid var(--border);">
        <div style="flex: 1; min-width: 200px;">
            <label class="form-label" style="font-size: 0.8rem; margin-bottom: 0.25rem; color: var(--text-muted);">Search Employee</label>
            <div style="position: relative;">
                <i class="fas fa-search" style="position: absolute; left: 0.75rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); font-size: 0.85rem;"></i>
                <input type="text" id="ot_filter_search" class="form-control" placeholder="Search by employee name or ID..." oninput="filterOvertimeApprovals()" style="padding-left: 2.25rem; font-size: 0.9rem; background: var(--bg-card); color: var(--text-main); border: 1px solid var(--border);">
            </div>
        </div>
        
        <div style="width: 160px;">
            <label class="form-label" style="font-size: 0.8rem; margin-bottom: 0.25rem; color: var(--text-muted);">Start Date</label>
            <input type="date" id="ot_filter_start" class="form-control" onchange="filterOvertimeApprovals()" style="font-size: 0.9rem; background: var(--bg-card); color: var(--text-main); border: 1px solid var(--border);">
        </div>
        
        <div style="width: 160px;">
            <label class="form-label" style="font-size: 0.8rem; margin-bottom: 0.25rem; color: var(--text-muted);">End Date</label>
            <input type="date" id="ot_filter_end" class="form-control" onchange="filterOvertimeApprovals()" style="font-size: 0.9rem; background: var(--bg-card); color: var(--text-main); border: 1px solid var(--border);">
        </div>
        
        <div style="width: 160px;">
            <label class="form-label" style="font-size: 0.8rem; margin-bottom: 0.25rem; color: var(--text-muted);">Status</label>
            <select id="ot_filter_status" class="form-control" onchange="filterOvertimeApprovals()" style="font-size: 0.9rem; background: var(--bg-card); color: var(--text-main); border: 1px solid var(--border);">
                <option value="all">All</option>
                <option value="pending">Pending</option>
                <option value="approved">Approved</option>
                <option value="rejected">Rejected</option>
            </select>
        </div>
        
        <div>
            <button class="btn" onclick="resetOvertimeFilters()" style="background: var(--bg-card); border: 1px solid var(--border); color: var(--text-muted); font-size: 0.9rem; padding: 0.5rem 1rem; cursor: pointer; display: flex; align-items: center; gap: 0.35rem; height: 38px;">
                <i class="fas fa-undo"></i> Reset
            </button>
        </div>
    </div>

    <!-- SUB-TAB 1: PENDING APPROVALS -->
    <div id="ot-pending-subtab" class="sub-tab-content" style="display: block;">
        <div class="card" style="padding: 1.5rem; margin-bottom: 1.5rem;">
            <h3 style="margin-top: 0; margin-bottom: 1.5rem; font-size: 1.1rem;"><i class="fas fa-hourglass-half" style="color: var(--warning); margin-right: 0.5rem;"></i> Pending Overtime Approvals</h3>
            
            <div class="table-container" style="overflow-x: auto;">
                <table class="table" style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="border-bottom: 2px solid var(--border); text-align: left;">
                            <th style="padding: 0.75rem 0.5rem; width: 100px;">Emp ID</th>
                            <th style="padding: 0.75rem 0.5rem;">Employee</th>
                            <th style="padding: 0.75rem 0.5rem;">Date</th>
                            <th style="padding: 0.75rem 0.5rem;">Hours</th>
                            <th style="padding: 0.75rem 0.5rem; width: 200px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="pendingOTTableBody">
                        <?php if (empty($pending_approvals)): ?>
                            <tr>
                                <td colspan="5" style="text-align: center; color: var(--text-muted); padding: 2rem;">No pending overtime approvals.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($pending_approvals as $req): ?>
                                <tr style="border-bottom: 1px solid var(--border);">
                                    <td style="padding: 0.75rem 0.5rem; font-family: monospace; font-weight: 700; color: var(--text-muted);"><?php echo e("EMP-" . str_pad($req['employee_id'], 4, '0', STR_PAD_LEFT)); ?></td>
                                    <td style="padding: 0.75rem 0.5rem; font-weight: 600;"><?php echo e($req['employee_name']); ?></td>
                                    <td style="padding: 0.75rem 0.5rem;"><?php echo e($req['date']); ?></td>
                                    <td style="padding: 0.75rem 0.5rem; font-weight: 600; color: var(--primary);"><?php echo number_format($req['hours'], 2); ?> Hrs</td>
                                    <td style="padding: 0.75rem 0.5rem;">
                                        <div style="display: flex; gap: 0.25rem;">
                                            <button class="btn" style="background: rgba(16, 185, 129, 0.1); color: #10B981; padding: 0.35rem 0.6rem; font-size: 0.8rem; font-weight: 600; cursor: pointer; border: none; border-radius: 4px;" onclick="openActionModal(<?php echo $req['id']; ?>, 'approved')">
                                                <i class="fas fa-check"></i> Approve
                                            </button>
                                            <button class="btn" style="background: rgba(239, 68, 68, 0.1); color: #EF4444; padding: 0.35rem 0.6rem; font-size: 0.8rem; font-weight: 600; cursor: pointer; border: none; border-radius: 4px;" onclick="openActionModal(<?php echo $req['id']; ?>, 'rejected')">
                                                <i class="fas fa-times"></i> Reject
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- SUB-TAB 2: PAST APPROVALS -->
    <div id="ot-past-subtab" class="sub-tab-content" style="display: none;">
        <div class="card" style="padding: 1.5rem;">
            <h3 style="margin-top: 0; margin-bottom: 1.5rem; font-size: 1.1rem;"><i class="fas fa-circle-check" style="color: var(--success); margin-right: 0.5rem;"></i> Past Overtime Approvals & Rejections</h3>
            
            <div class="table-container" style="overflow-x: auto;">
                <table class="table" style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="border-bottom: 2px solid var(--border); text-align: left;">
                            <th style="padding: 0.75rem 0.5rem; width: 100px;">Emp ID</th>
                            <th style="padding: 0.75rem 0.5rem;">Employee</th>
                            <th style="padding: 0.75rem 0.5rem;">Date</th>
                            <th style="padding: 0.75rem 0.5rem;">Hours</th>
                            <th style="padding: 0.75rem 0.5rem;">Status</th>
                            <th style="padding: 0.75rem 0.5rem;">Comments</th>
                        </tr>
                    </thead>
                    <tbody id="pastOTTableBody">
                        <?php if (empty($past_approvals)): ?>
                            <tr>
                                <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 2rem;">No past overtime records processed.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($past_approvals as $req): ?>
                                <tr style="border-bottom: 1px solid var(--border);">
                                    <td style="padding: 0.75rem 0.5rem; font-family: monospace; font-weight: 700; color: var(--text-muted);"><?php echo e("EMP-" . str_pad($req['employee_id'], 4, '0', STR_PAD_LEFT)); ?></td>
                                    <td style="padding: 0.75rem 0.5rem; font-weight: 600;"><?php echo e($req['employee_name']); ?></td>
                                    <td style="padding: 0.75rem 0.5rem;"><?php echo e($req['date']); ?></td>
                                    <td style="padding: 0.75rem 0.5rem; font-weight: 600; color: var(--primary);"><?php echo number_format($req['hours'], 2); ?> Hrs</td>
                                    <td style="padding: 0.75rem 0.5rem;">
                                        <?php
                                        $bg = 'rgba(0,0,0,0.05)';
                                        $fg = 'var(--text-muted)';
                                        if ($req['status'] === 'approved') {
                                            $bg = 'rgba(16, 185, 129, 0.1)';
                                            $fg = '#10B981';
                                        } elseif ($req['status'] === 'rejected') {
                                            $bg = 'rgba(239, 68, 68, 0.1)';
                                            $fg = '#EF4444';
                                        }
                                        ?>
                                        <span class="badge" style="
                                            background: <?php echo $bg; ?>; color: <?php echo $fg; ?>;
                                            padding: 0.25rem 0.5rem; border-radius: 6px; font-size: 0.75rem; text-transform: uppercase; font-weight: 600;
                                        "><?php echo e($req['status']); ?></span>
                                    </td>
                                    <td style="padding: 0.75rem 0.5rem; font-size: 0.85rem; color: var(--text-muted);"><?php echo e($req['comments'] ?: '-'); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- ACTION MODAL -->
<div id="actionModal" style="display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 10000; align-items: center; justify-content: center; backdrop-filter: blur(4px);">
    <div class="card" style="width: 450px; padding: 1.5rem; box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1); background: var(--bg-card); border: 1px solid var(--border);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
            <h3 id="modalTitle" style="margin: 0; font-size: 1.15rem; color: var(--text-main);">Process Overtime Request</h3>
            <button onclick="closeActionModal()" style="background: none; border: none; font-size: 1.25rem; color: var(--text-muted); cursor: pointer;"><i class="fas fa-times"></i></button>
        </div>
        <form id="actionForm" onsubmit="submitAction(event)">
            <input type="hidden" id="actionRequestId" name="id">
            <input type="hidden" id="actionStatus" name="status">
            
            <div class="form-group" style="margin-bottom: 1.25rem;">
                <label class="form-label" for="actionComments" style="color: var(--text-main);">Comments / Feedback</label>
                <textarea id="actionComments" class="form-control" name="comments" rows="3" placeholder="Reason for approval or rejection..." required style="background: var(--bg-card); color: var(--text-main); border: 1px solid var(--border);"></textarea>
            </div>
            
            <div style="display: flex; justify-content: flex-end; gap: 0.5rem;">
                <button type="button" class="btn" style="background: var(--bg-card); border: 1px solid var(--border); cursor: pointer; color: var(--text-muted);" onclick="closeActionModal()">Cancel</button>
                <button type="submit" id="submitBtn" class="btn" style="background: var(--primary); color: white; cursor: pointer;">Submit</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- Photo Preview Modal -->
<div id="photoModal" style="display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 10000; align-items: center; justify-content: center; backdrop-filter: blur(4px);">
    <div class="card" style="width: 450px; padding: 1.5rem; box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1); background: var(--bg-card); border: 1px solid var(--border); text-align: center;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
            <h3 id="photoModalTitle" style="margin: 0; font-size: 1.15rem; color: var(--text-main);">Verification Photo</h3>
            <button onclick="closePhotoModal()" style="background: none; border: none; font-size: 1.25rem; color: var(--text-muted); cursor: pointer;"><i class="fas fa-times"></i></button>
        </div>
        <div style="width: 100%; aspect-ratio: 4/3; background: #000; border-radius: 12px; overflow: hidden; border: 1px solid var(--border); margin-bottom: 1rem;">
            <img id="photoModalImg" src="" alt="Clock Verification" style="width: 100%; height: 100%; object-fit: cover;">
        </div>
        <div id="photoModalLabel" style="font-size: 0.9rem; color: var(--text-muted); font-weight: 500;">Clock Details</div>
    </div>
</div>

<script>
const currentEmployeeId = <?php echo json_encode($my_id); ?>;
let clockInTime = null;
let timerInterval = null;

// Overtime approvals cache and filtering
const cachedPendingApprovals = <?php echo json_encode($pending_approvals); ?>;
const cachedPastApprovals = <?php echo json_encode($past_approvals); ?>;

const escapeHtml = (str) => {
    if (!str) return '';
    return str.toString()
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
};

function viewPhoto(url, name, label) {
    document.getElementById('photoModalImg').src = url;
    document.getElementById('photoModalTitle').innerText = name;
    document.getElementById('photoModalLabel').innerText = label;
    document.getElementById('photoModal').style.display = 'flex';
}

function closePhotoModal() {
    document.getElementById('photoModal').style.display = 'none';
}

function filterOvertimeApprovals() {
    const queryInput = document.getElementById('ot_filter_search');
    const query = queryInput ? queryInput.value.toLowerCase().trim() : '';
    
    const startInput = document.getElementById('ot_filter_start');
    const startDate = startInput ? startInput.value : '';
    
    const endInput = document.getElementById('ot_filter_end');
    const endDate = endInput ? endInput.value : '';
    
    const statusSelect = document.getElementById('ot_filter_status');
    const selectedStatus = statusSelect ? statusSelect.value : 'all';
    
    const filterItem = (req) => {
        // Name/ID query match
        if (query) {
            const nameMatch = req.employee_name && req.employee_name.toLowerCase().includes(query);
            const idMatch = req.employee_id && req.employee_id.toString().includes(query);
            if (!nameMatch && !idMatch) return false;
        }
        
        // Date range match
        if (startDate && req.date < startDate) return false;
        if (endDate && req.date > endDate) return false;
        
        // Status match
        if (selectedStatus !== 'all' && req.status !== selectedStatus) return false;
        
        return true;
    };
    
    const filteredPending = cachedPendingApprovals.filter(filterItem);
    const filteredPast = cachedPastApprovals.filter(filterItem);
    
    renderPendingApprovals(filteredPending);
    renderPastApprovals(filteredPast);
}

function resetOvertimeFilters() {
    const queryInput = document.getElementById('ot_filter_search');
    if (queryInput) queryInput.value = '';
    
    const startInput = document.getElementById('ot_filter_start');
    if (startInput) startInput.value = '';
    
    const endInput = document.getElementById('ot_filter_end');
    if (endInput) endInput.value = '';
    
    const statusSelect = document.getElementById('ot_filter_status');
    if (statusSelect) statusSelect.value = 'all';
    
    filterOvertimeApprovals();
}

function renderPendingApprovals(list) {
    const tbody = document.getElementById('pendingOTTableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    // Update badge count
    const badge = document.getElementById('pendingOTCountBadge');
    if (badge) {
        const pendingCount = list.filter(r => r.status === 'pending').length;
        if (pendingCount > 0) {
            badge.style.display = 'inline-block';
            badge.textContent = pendingCount;
        } else {
            badge.style.display = 'none';
        }
    }
    
    if (list.length === 0) {
        tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 2rem;">No pending overtime approvals found.</td></tr>`;
        return;
    }
    
    list.forEach(req => {
        const tr = document.createElement('tr');
        tr.style.borderBottom = '1px solid var(--border)';
        
        tr.innerHTML = `
            <td style="padding: 0.75rem 0.5rem; font-family: monospace; font-weight: 700; color: var(--text-muted);">EMP-${String(req.employee_id).padStart(4, '0')}</td>
            <td style="padding: 0.75rem 0.5rem; font-weight: 600; color: var(--text-main);">${escapeHtml(req.employee_name)}</td>
            <td style="padding: 0.75rem 0.5rem; color: var(--text-muted);">${escapeHtml(req.date)}</td>
            <td style="padding: 0.75rem 0.5rem; font-weight: 600; color: var(--primary);">${parseFloat(req.hours).toFixed(2)} Hrs</td>
            <td style="padding: 0.75rem 0.5rem;">
                <div style="display: flex; gap: 0.25rem;">
                    <button class="btn" style="background: rgba(16, 185, 129, 0.1); color: #10B981; padding: 0.35rem 0.6rem; font-size: 0.8rem; font-weight: 600; cursor: pointer; border: none; border-radius: 4px;" onclick="openActionModal(${req.id}, 'approved')">
                        <i class="fas fa-check"></i> Approve
                    </button>
                    <button class="btn" style="background: rgba(239, 68, 68, 0.1); color: #EF4444; padding: 0.35rem 0.6rem; font-size: 0.8rem; font-weight: 600; cursor: pointer; border: none; border-radius: 4px;" onclick="openActionModal(${req.id}, 'rejected')">
                        <i class="fas fa-times"></i> Reject
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

function renderPastApprovals(list) {
    const tbody = document.getElementById('pastOTTableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    if (list.length === 0) {
        tbody.innerHTML = `<tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 2rem;">No past overtime records found.</td></tr>`;
        return;
    }
    
    list.forEach(req => {
        const tr = document.createElement('tr');
        tr.style.borderBottom = '1px solid var(--border)';
        
        let bg = 'rgba(0,0,0,0.05)';
        let fg = 'var(--text-muted)';
        if (req.status === 'approved') {
            bg = 'rgba(16, 185, 129, 0.1)';
            fg = '#10B981';
        } else if (req.status === 'rejected') {
            bg = 'rgba(239, 68, 68, 0.1)';
            fg = '#EF4444';
        }
        
        tr.innerHTML = `
            <td style="padding: 0.75rem 0.5rem; font-family: monospace; font-weight: 700; color: var(--text-muted);">EMP-${String(req.employee_id).padStart(4, '0')}</td>
            <td style="padding: 0.75rem 0.5rem; font-weight: 600; color: var(--text-main);">${escapeHtml(req.employee_name)}</td>
            <td style="padding: 0.75rem 0.5rem; color: var(--text-muted);">${escapeHtml(req.date)}</td>
            <td style="padding: 0.75rem 0.5rem; font-weight: 600; color: var(--primary);">${parseFloat(req.hours).toFixed(2)} Hrs</td>
            <td style="padding: 0.75rem 0.5rem;">
                <span class="badge" style="
                    background: ${bg}; color: ${fg};
                    padding: 0.25rem 0.5rem; border-radius: 6px; font-size: 0.75rem; text-transform: uppercase; font-weight: 600;
                ">${escapeHtml(req.status)}</span>
            </td>
            <td style="padding: 0.75rem 0.5rem; font-size: 0.85rem; color: var(--text-muted);">${escapeHtml(req.comments || '-')}</td>
        `;
        tbody.appendChild(tr);
    });
}

// Tab switcher
function switchTab(tabId, btn) {
    document.querySelectorAll('.tab-content').forEach(content => content.style.display = 'none');
    document.querySelectorAll('.tab-btn').forEach(button => button.classList.remove('active'));
    document.getElementById(tabId).style.display = 'block';
    btn.classList.add('active');
}

function switchSubTab(subTabId, btn) {
    document.querySelectorAll('.sub-tab-content').forEach(content => content.style.display = 'none');
    document.querySelectorAll('.sub-tab-btn').forEach(button => button.classList.remove('active'));
    document.getElementById(subTabId).style.display = 'block';
    btn.classList.add('active');
}

// Digital clock live display
function updateDigitalClock() {
    const el = document.getElementById('digitalClock');
    if (!el) return;
    const now = new Date();
    let hours = now.getHours();
    let minutes = now.getMinutes();
    let seconds = now.getSeconds();
    const ampm = hours >= 12 ? 'PM' : 'AM';
    
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    
    el.innerText = `${hours}:${minutes}:${seconds} ${ampm}`;
}

// Check current status on load
async function checkAttendanceStatus() {
    const todayHoursText = document.getElementById('todayHoursText');
    if (!todayHoursText) return;
    
    const res = await apiCall('attendance', { action: 'status' });
    if (res.success) {
        todayHoursText.innerText = res.today_hours;
        
        if (res.is_clocked_in) {
            document.getElementById('clockStatusText').innerText = `Checked In since ${res.clock_in_time}`;
            document.getElementById('clockStatusCard').style.borderColor = 'rgba(16, 185, 129, 0.4)';
            document.getElementById('clockStatusCard').style.background = 'rgba(16, 185, 129, 0.05)';
            
            document.getElementById('btnClockIn').style.display = 'none';
            document.getElementById('btnClockOut').style.display = 'block';
            
            // Start timer
            clockInTime = new Date(`${res.clock_in_date}T${res.clock_in_time}`);
            document.getElementById('shiftTimer').style.display = 'block';
            startShiftTimer();
        } else {
            document.getElementById('clockStatusText').innerText = 'Not Clocked In';
            document.getElementById('clockStatusCard').style.borderColor = 'var(--border)';
            document.getElementById('clockStatusCard').style.background = 'rgba(0,0,0,0.02)';
            
            document.getElementById('btnClockIn').style.display = 'block';
            document.getElementById('btnClockOut').style.display = 'none';
            
            document.getElementById('shiftTimer').style.display = 'none';
            stopShiftTimer();
        }
    } else {
        document.getElementById('clockStatusText').innerText = 'Unable to check status';
    }
}

function startShiftTimer() {
    if (timerInterval) clearInterval(timerInterval);
    
    timerInterval = setInterval(() => {
        const now = new Date();
        const diffMs = now - clockInTime;
        if (diffMs < 0) return; // Timezone or server discrepancy
        
        const diffSecs = Math.floor(diffMs / 1000);
        const hours = Math.floor(diffSecs / 3600);
        const minutes = Math.floor((diffSecs % 3600) / 60);
        const seconds = diffSecs % 60;
        
        const pad = (num) => num.toString().padStart(2, '0');
        document.getElementById('shiftTimer').innerText = `Duration: ${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
    }, 1000);
}

function stopShiftTimer() {
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
}

// Clock IN or OUT click action
async function triggerClock(action) {
    const btn = action === 'clock_in' ? document.getElementById('btnClockIn') : document.getElementById('btnClockOut');
    setLoading(btn, true);
    
    const res = await apiCall('attendance', { action: action });
    setLoading(btn, false);
    
    if (res.success) {
        notify(res.message, 'success');
        setTimeout(() => window.location.reload(), 1000);
    } else {
        notify(res.message, 'error');
    }
}

// Manager functions
const employeesData = <?php echo json_encode($employees); ?>;

function openAddManualLogModal() {
    document.getElementById('modalTitle').innerText = 'Add Manual Clock Log';
    document.getElementById('log_id').value = '';
    document.getElementById('manualLogForm').reset();
    document.getElementById('log_employee_id').value = '';
    document.getElementById('employee_search_input').value = '';
    document.getElementById('employee_search_input').disabled = false;
    document.getElementById('log_date').value = '<?php echo date('Y-m-d'); ?>';
    openModal('manualLogModal');
}

function editAttendance(log) {
    document.getElementById('modalTitle').innerText = 'Edit Attendance Log';
    document.getElementById('log_id').value = log.id;
    document.getElementById('log_employee_id').value = log.employee_id;
    document.getElementById('log_date').value = log.date;
    
    // Find employee name
    const emp = employeesData.find(e => e.id == log.employee_id);
    document.getElementById('employee_search_input').value = emp ? emp.name : (log.employee_name || '');
    document.getElementById('employee_search_input').disabled = true;
    
    // Extract times
    const clockInTime = log.clock_in ? log.clock_in.split(' ')[1].substring(0, 5) : '';
    const clockOutTime = log.clock_out ? log.clock_out.split(' ')[1].substring(0, 5) : '';
    
    document.getElementById('log_clock_in').value = clockInTime;
    document.getElementById('log_clock_out').value = clockOutTime;
    document.getElementById('log_status').value = log.status;
    
    openModal('manualLogModal');
}

async function saveManualLog(e) {
    e.preventDefault();
    const form = document.getElementById('manualLogForm');
    const formData = new FormData(form);
    
    // Convert to JSON
    const data = {
        action: 'manual_log',
        id: formData.get('id'),
        employee_id: formData.get('employee_id'),
        date: formData.get('date'),
        clock_in: formData.get('clock_in'),
        clock_out: formData.get('clock_out'),
        status: formData.get('status')
    };
    
    const submitBtn = form.querySelector('button[type="submit"]');
    setLoading(submitBtn, true);
    
    const res = await apiCall('attendance', data);
    setLoading(submitBtn, false);
    
    if (res.success) {
        notify(res.message, 'success');
        closeModal('manualLogModal');
        setTimeout(() => window.location.reload(), 1000);
    } else {
        notify(res.message, 'error');
    }
}

async function deleteAttendance(id) {
    const proceed = await confirmAction({
        title: 'Delete Attendance Log',
        message: 'Are you sure you want to permanently delete this clock log?',
        confirmText: 'Delete'
    });
    
    if (proceed) {
        const res = await apiCall('attendance', { action: 'delete_log', id: id });
        if (res.success) {
            notify(res.message, 'success');
            setTimeout(() => window.location.reload(), 1000);
        } else {
            notify(res.message, 'error');
        }
    }
}

async function loadMyLogs() {
    const startInput = document.getElementById('my_logs_start');
    const endInput = document.getElementById('my_logs_end');
    if (!startInput || !endInput) return;
    
    const startDate = startInput.value;
    const endDate = endInput.value;
    
    const tbody = document.getElementById('myLogsTableBody');
    tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 2rem;"><i class="fas fa-spinner fa-spin" style="margin-right: 0.5rem;"></i>Loading logs...</td></tr>';
    
    const res = await apiCall('attendance', {
        action: 'my_logs',
        start_date: startDate,
        end_date: endDate
    });
    
    if (res.success) {
        tbody.innerHTML = '';
        if (res.logs.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 2rem;">No clock logs found for the selected period.</td></tr>';
            return;
        }
        
        const grouped = {};
        res.logs.forEach(log => {
            if (!grouped[log.date]) {
                grouped[log.date] = [];
            }
            grouped[log.date].push(log);
        });
        
        Object.entries(grouped).forEach(([date, logs]) => {
            const headerRow = document.createElement('tr');
            headerRow.style.background = 'rgba(99, 102, 241, 0.04)';
            headerRow.style.borderBottom = '1px solid var(--border)';
            headerRow.innerHTML = `
                <td colspan="5" style="padding: 0.75rem 0.5rem; font-weight: 700; color: var(--primary); font-size: 0.9rem;">
                    <i class="fas fa-calendar-day" style="margin-right: 0.5rem;"></i>${date}
                </td>
            `;
            tbody.appendChild(headerRow);
            
            logs.forEach(log => {
                const tr = document.createElement('tr');
                tr.style.borderBottom = '1px solid var(--border)';
                
                const formatTime = (timeStr) => {
                    if (!timeStr) return '';
                    const t = timeStr.split(' ')[1] || timeStr;
                    const parts = t.split(':');
                    let h = parseInt(parts[0]);
                    const m = parts[1];
                    const ampm = h >= 12 ? 'PM' : 'AM';
                    h = h % 12;
                    h = h ? h : 12;
                    return `${h}:${m} ${ampm}`;
                };
                
                const inTime = formatTime(log.clock_in);
                const outTime = log.clock_out ? formatTime(log.clock_out) : '<span style="color: var(--primary);">Active</span>';
                
                let hoursWorked = '-';
                if (log.clock_out) {
                    const diffMs = new Date(log.clock_out.replace(' ', 'T')) - new Date(log.clock_in.replace(' ', 'T'));
                    if (!isNaN(diffMs)) {
                        hoursWorked = (diffMs / 3600000).toFixed(2);
                    }
                }
                
                const badgeBg = log.status === 'present' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(245, 158, 11, 0.1)';
                const badgeColor = log.status === 'present' ? '#10B981' : '#F59E0B';
                
                let lateBadge = '';
                if (log.is_late) {
                    lateBadge = `<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #EF4444; padding: 0.25rem 0.5rem; border-radius: 6px; font-size: 0.75rem; font-weight: 600; margin-left: 0.5rem;"><i class="fas fa-exclamation-circle" style="margin-right: 0.25rem;"></i>LATE</span>`;
                }
                
                const sourceLabel = log.source.replace('_', ' ').replace(/\b\w/g, c => c.toUpperCase());
                
                const inPhotoHtml = log.clock_in_photo 
                    ? `<span style="margin-left: 0.4rem; color: var(--primary); cursor: pointer;" title="View Verification Photo" onclick="viewPhoto('${log.clock_in_photo}', '${escapeHtml(log.employee_name || 'My Clock In')}', 'Clock In - ${log.date} ${inTime}')"><i class="fas fa-camera"></i></span>`
                    : '';
                const outPhotoHtml = (log.clock_out && log.clock_out_photo)
                    ? `<span style="margin-left: 0.4rem; color: var(--primary); cursor: pointer;" title="View Verification Photo" onclick="viewPhoto('${log.clock_out_photo}', '${escapeHtml(log.employee_name || 'My Clock Out')}', 'Clock Out - ${log.date} ${outTime}')"><i class="fas fa-camera"></i></span>`
                    : '';
                
                tr.innerHTML = `
                    <td style="padding: 0.75rem 0.5rem; color: #10B981; font-weight: 600;"><span style="display: inline-flex; align-items: center;">${inTime}${inPhotoHtml}</span></td>
                    <td style="padding: 0.75rem 0.5rem; color: #EF4444; font-weight: 600;"><span style="display: inline-flex; align-items: center;">${outTime}${outPhotoHtml}</span></td>
                    <td style="padding: 0.75rem 0.5rem;">
                        <span class="badge" style="background: ${badgeBg}; color: ${badgeColor}; padding: 0.25rem 0.5rem; border-radius: 6px; font-size: 0.75rem; text-transform: uppercase; font-weight: 600;">
                            ${log.status}
                        </span>
                        ${lateBadge}
                    </td>
                    <td style="padding: 0.75rem 0.5rem; font-size: 0.85rem; color: var(--text-muted);">${sourceLabel}</td>
                    <td style="padding: 0.75rem 0.5rem; font-family: monospace; font-weight: 700;">${hoursWorked}</td>
                `;
                tbody.appendChild(tr);
            });
        });
    } else {
        notify(res.message, 'error');
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--danger); padding: 2rem;">Error loading logs.</td></tr>';
    }
}

function getLocalDateString(dateObj = new Date()) {
    const year = dateObj.getFullYear();
    const month = String(dateObj.getMonth() + 1).padStart(2, '0');
    const day = String(dateObj.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

function toggleEmployeeGroup(groupId, headerEl) {
    const rows = document.querySelectorAll(`.${groupId}`);
    const icon = headerEl.querySelector('.group-icon');
    const isExpanded = icon.style.transform === 'rotate(90deg)';
    
    rows.forEach(row => {
        row.style.display = isExpanded ? 'none' : 'table-row';
    });
    icon.style.transform = isExpanded ? 'rotate(0deg)' : 'rotate(90deg)';
}

let cachedAllLogs = [];

async function loadAllLogs() {
    const startInput = document.getElementById('all_logs_start');
    const endInput = document.getElementById('all_logs_end');
    if (!startInput || !endInput) return;
    
    const startDate = startInput.value;
    const endDate = endInput.value;
    
    const tbody = document.getElementById('allLogsTableBody');
    tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 2rem;"><i class="fas fa-spinner fa-spin" style="margin-right: 0.5rem;"></i>Loading logs...</td></tr>';
    
    const res = await apiCall('attendance', {
        action: 'all_logs',
        start_date: startDate,
        end_date: endDate
    });
    
    if (res.success) {
        cachedAllLogs = res.logs;
        filterAllLogs();
    } else {
        notify(res.message, 'error');
        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--danger); padding: 2rem;">Error loading logs.</td></tr>';
    }
}

function filterAllLogs() {
    const queryInput = document.getElementById('all_logs_search');
    const query = queryInput ? queryInput.value.toLowerCase().trim() : '';
    
    const statusInput = document.getElementById('all_logs_status');
    const selectedStatus = statusInput ? statusInput.value : 'all';
    
    const filtered = cachedAllLogs.filter(log => {
        // Search query check
        let matchesQuery = true;
        if (query) {
            const nameMatch = log.employee_name && log.employee_name.toLowerCase().includes(query);
            const idMatch = log.employee_id && log.employee_id.toString().includes(query);
            matchesQuery = nameMatch || idMatch;
        }
        
        // Status check
        let matchesStatus = true;
        if (selectedStatus !== 'all') {
            if (selectedStatus === 'late') {
                matchesStatus = log.is_late ? true : false;
            } else {
                matchesStatus = log.status === selectedStatus;
            }
        }
        
        return matchesQuery && matchesStatus;
    });
    
    renderAllLogs(filtered);
}

function renderAllLogs(logs) {
    const tbody = document.getElementById('allLogsTableBody');
    if (!tbody) return;
    tbody.innerHTML = '';
    
    if (logs.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 2rem;">No attendance records found.</td></tr>';
        return;
    }
    
    const grouped = {};
    logs.forEach(log => {
        if (!grouped[log.employee_id]) {
            grouped[log.employee_id] = {
                name: log.employee_name,
                logs: []
            };
        }
        grouped[log.employee_id].logs.push(log);
    });
    
    let groupIndex = 0;
    Object.entries(grouped).forEach(([empId, group]) => {
        groupIndex++;
        const groupId = `emp-group-${groupIndex}`;
        
        const headerRow = document.createElement('tr');
        headerRow.className = 'employee-group-header';
        headerRow.style.cssText = 'cursor: pointer; background: rgba(99, 102, 241, 0.04); font-weight: bold; border-bottom: 1px solid var(--border);';
        headerRow.innerHTML = `
            <td colspan="7" style="padding: 0.75rem 0.5rem; font-weight: 700; color: var(--text-color);">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>
                        <i class="fas fa-chevron-right group-icon" style="margin-right: 0.5rem; transition: transform 0.2s; transform: rotate(90deg);"></i>
                        ${escapeHtml(group.name)} <span style="font-size: 0.8rem; color: var(--text-muted); font-weight: normal; margin-left: 0.5rem;">[ID: EMP-${String(empId).padStart(4, '0')}]</span>
                    </span>
                    <span class="badge" style="background: var(--glass-bg); padding: 0.15rem 0.5rem; border-radius: 6px; font-size: 0.75rem; color: var(--text-muted);">${group.logs.length} Log${group.logs.length > 1 ? 's' : ''}</span>
                </div>
            </td>
        `;
        headerRow.addEventListener('click', () => toggleEmployeeGroup(groupId, headerRow));
        tbody.appendChild(headerRow);
        
        group.logs.forEach(log => {
            const tr = document.createElement('tr');
            tr.className = groupId;
            tr.style.cssText = 'border-bottom: 1px solid var(--border); display: table-row;';
            
            const formatTime = (timeStr) => {
                if (!timeStr) return '';
                const t = timeStr.split(' ')[1] || timeStr;
                const parts = t.split(':');
                let h = parseInt(parts[0]);
                const m = parts[1];
                const ampm = h >= 12 ? 'PM' : 'AM';
                h = h % 12;
                h = h ? h : 12;
                return `${h}:${m} ${ampm}`;
            };
            
            const inTime = formatTime(log.clock_in);
            const outTime = log.clock_out ? formatTime(log.clock_out) : '<span style="color: var(--primary);">Active</span>';
            
            let hoursWorked = '-';
            if (log.clock_out) {
                const diffMs = new Date(log.clock_out.replace(' ', 'T')) - new Date(log.clock_in.replace(' ', 'T'));
                if (!isNaN(diffMs)) {
                    hoursWorked = (diffMs / 3600000).toFixed(2);
                }
            }
            
            const badgeBg = log.status === 'present' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(245, 158, 11, 0.1)';
            const badgeColor = log.status === 'present' ? '#10B981' : '#F59E0B';
            
            let lateBadge = '';
            if (log.is_late) {
                lateBadge = `<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #EF4444; padding: 0.25rem 0.5rem; border-radius: 6px; font-size: 0.75rem; font-weight: 600; margin-left: 0.5rem;"><i class="fas fa-exclamation-circle" style="margin-right: 0.25rem;"></i>LATE</span>`;
            }
            
            const sourceLabel = log.source.replace('_', ' ').replace(/\b\w/g, c => c.toUpperCase());
            
            const escapedLog = JSON.stringify(log).replace(/"/g, '&quot;');
            
            const inPhotoHtml = log.clock_in_photo 
                ? `<span style="margin-left: 0.4rem; color: var(--primary); cursor: pointer;" title="View Verification Photo" onclick="viewPhoto('${log.clock_in_photo}', '${escapeHtml(group.name || 'Employee')}', 'Clock In - ${log.date} ${inTime}')"><i class="fas fa-camera"></i></span>`
                : '';
            const outPhotoHtml = (log.clock_out && log.clock_out_photo)
                ? `<span style="margin-left: 0.4rem; color: var(--primary); cursor: pointer;" title="View Verification Photo" onclick="viewPhoto('${log.clock_out_photo}', '${escapeHtml(group.name || 'Employee')}', 'Clock Out - ${log.date} ${outTime}')"><i class="fas fa-camera"></i></span>`
                : '';
            
            tr.innerHTML = `
                <td style="padding: 0.75rem 0.5rem; font-weight: 600; padding-left: 2rem;">${log.date}</td>
                <td style="padding: 0.75rem 0.5rem; color: #10B981; font-weight: 600;"><span style="display: inline-flex; align-items: center;">${inTime}${inPhotoHtml}</span></td>
                <td style="padding: 0.75rem 0.5rem; color: #EF4444; font-weight: 600;"><span style="display: inline-flex; align-items: center;">${outTime}${outPhotoHtml}</span></td>
                <td style="padding: 0.75rem 0.5rem;">
                    <span class="badge" style="background: ${badgeBg}; color: ${badgeColor}; padding: 0.25rem 0.5rem; border-radius: 6px; font-size: 0.75rem; text-transform: uppercase; font-weight: 600;">
                        ${log.status}
                    </span>
                    ${lateBadge}
                </td>
                <td style="padding: 0.75rem 0.5rem; font-size: 0.85rem; color: var(--text-muted);">${sourceLabel}</td>
                <td style="padding: 0.75rem 0.5rem; font-family: monospace; font-weight: 700;">${hoursWorked}</td>
                <td style="padding: 0.75rem 0.5rem; text-align: right;">
                    ${log.employee_id != currentEmployeeId ? `
                    <div style="display: inline-flex; gap: 0.5rem;">
                        <button class="btn btn-icon" style="background: rgba(99, 102, 241, 0.1); color: var(--primary);" onclick="editAttendance(${escapedLog})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-icon" style="background: rgba(239, 68, 68, 0.1); color: var(--danger);" onclick="deleteAttendance(${log.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                    ` : ''}
                </td>
            `;
            tbody.appendChild(tr);
        });
    });
}

// Initialise
document.addEventListener('DOMContentLoaded', () => {
    setInterval(updateDigitalClock, 1000);
    updateDigitalClock();
    checkAttendanceStatus();
    
    // Set default filter dates local to the client
    const endInput = document.getElementById('my_logs_end');
    const startInput = document.getElementById('my_logs_start');
    if (endInput && startInput) {
        const todayStr = getLocalDateString();
        endInput.value = todayStr;
        startInput.value = todayStr;
        loadMyLogs();
    }
    
    const allEndInput = document.getElementById('all_logs_end');
    const allStartInput = document.getElementById('all_logs_start');
    if (allEndInput && allStartInput) {
        const todayStr = getLocalDateString();
        allEndInput.value = todayStr;
        allStartInput.value = todayStr;
        loadAllLogs();
    }
    
    // Autocomplete Logic
    const searchInput = document.getElementById('employee_search_input');
    const hiddenInput = document.getElementById('log_employee_id');
    const suggestionsDiv = document.getElementById('employee_suggestions');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const query = this.value.toLowerCase().trim();
            suggestionsDiv.innerHTML = '';
            
            if (!query) {
                suggestionsDiv.style.display = 'none';
                hiddenInput.value = '';
                return;
            }
            
            const matches = employeesData.filter(emp => emp.name.toLowerCase().includes(query));
            if (matches.length === 0) {
                suggestionsDiv.innerHTML = '<div style="padding: 0.75rem; color: var(--text-muted); font-size: 0.85rem; text-align: center;">No employees found</div>';
                suggestionsDiv.style.display = 'block';
                hiddenInput.value = '';
                return;
            }
            
            matches.forEach(emp => {
                const item = document.createElement('div');
                item.style.cssText = 'padding: 0.75rem 1rem; cursor: pointer; transition: background 0.2s; font-size: 0.875rem; color: var(--text-main); border-bottom: 1px solid var(--border);';
                item.innerHTML = emp.name;
                item.addEventListener('mouseenter', () => item.style.background = 'var(--glass-bg)');
                item.addEventListener('mouseleave', () => item.style.background = 'transparent');
                
                item.addEventListener('click', () => {
                    searchInput.value = emp.name;
                    hiddenInput.value = emp.id;
                    suggestionsDiv.style.display = 'none';
                });
                suggestionsDiv.appendChild(item);
            });
            suggestionsDiv.style.display = 'block';
        });
        
        document.addEventListener('click', function(e) {
            if (e.target !== searchInput && e.target !== suggestionsDiv) {
                suggestionsDiv.style.display = 'none';
            }
        });
    }
});

function openActionModal(id, status) {
    document.getElementById('actionRequestId').value = id;
    document.getElementById('actionStatus').value = status;
    document.getElementById('actionComments').value = '';
    
    const title = status === 'approved' ? 'Approve Overtime Request' : 'Reject Overtime Request';
    document.getElementById('modalTitle').textContent = title;
    
    const submitBtn = document.getElementById('submitBtn');
    if (status === 'approved') {
        submitBtn.style.background = '#10B981';
        submitBtn.textContent = 'Approve';
    } else {
        submitBtn.style.background = '#EF4444';
        submitBtn.textContent = 'Reject';
    }
    
    document.getElementById('actionModal').style.display = 'flex';
}

function closeActionModal() {
    document.getElementById('actionModal').style.display = 'none';
}

function submitAction(e) {
    e.preventDefault();
    
    const id = document.getElementById('actionRequestId').value;
    const status = document.getElementById('actionStatus').value;
    const comments = document.getElementById('actionComments').value;
    
    fetch('api/overtime.php?action=update_status', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id, status, comments })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            closeActionModal();
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(err => {
        console.error(err);
        alert('An error occurred. Please try again.');
    });
}
</script>
