<?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']);

// Fetch my employee details
$me = fetch("SELECT id, reporting_manager_id FROM employees WHERE user_id = ? AND company_id = ?", [$user_id, $company_id]);
$my_id = $me ? $me['id'] : null;

// 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 holiday calendar
$holidays = fetchAll("SELECT * FROM public_holidays WHERE company_id = ? ORDER BY holiday_date ASC", [$company_id]);

// Fetch configurations
$configs = fetchAll("SELECT * FROM leave_configurations WHERE company_id = ?", [$company_id]);
$limits = [
    'casual' => 0,
    'annual' => 0,
    'sick' => 0,
    'maternity' => 0,
    'paternity' => 0
];
foreach ($configs as $c) {
    $limits[$c['leave_type']] = intval($c['days_per_year']);
}

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

// Fetch pending approvals for this manager
$pending_requests = [];
if ($is_mgr) {
    // Show requests where the logged-in user is the designated reporting manager
    $pending_requests = fetchAll("
        SELECT r.*, e.name as employee_name, m.name as manager_name 
        FROM leave_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 = ? AND r.reporting_manager_id = ? AND r.status = 'pending'
        ORDER BY r.created_at ASC
    ", [$company_id, $user_id]);
}
?>

<div style="display: flex; justify-content: flex-end; margin-bottom: 2rem;">
    <?php if ($my_id): ?>
    <button class="btn" style="background: var(--primary); color: white;" onclick="openApplyLeaveModal()">
        <i class="fas fa-plus" style="margin-right: 0.5rem;"></i>Apply for Leave
    </button>
    <?php endif; ?>
</div>

<!-- 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 (!hasRole('owner')): ?>
        <button class="btn tab-btn active" onclick="switchTab('my-leaves-tab', this)">
            <i class="fas fa-calendar-check" style="margin-right: 0.5rem;"></i>My Leaves
        </button>
        <?php endif; ?>
        <?php if ($is_mgr): ?>
        <button class="btn tab-btn <?php echo hasRole('owner') ? 'active' : ''; ?>" onclick="switchTab('approvals-tab', this)">
            <i class="fas fa-tasks" style="margin-right: 0.5rem;"></i>Approvals
            <?php if (count($pending_requests) > 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 count($pending_requests); ?></span>
            <?php endif; ?>
        </button>
        <button class="btn tab-btn" onclick="switchTab('company-records-tab', this)">
            <i class="fas fa-folder-open" style="margin-right: 0.5rem;"></i>Company Leave Records
        </button>
        <button class="btn tab-btn" onclick="switchTab('leave-config-tab', this)">
            <i class="fas fa-sliders" style="margin-right: 0.5rem;"></i>Configurations
        </button>
        <?php endif; ?>
    </div>
</div>

<!-- TAB 1: MY LEAVES -->
<?php if (!hasRole('owner')): ?>
<div id="my-leaves-tab" class="tab-content active-content">
    <!-- Balances row -->
    <div id="leaveBalancesRow" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; margin-bottom: 1.5rem;">
        <!-- Filled dynamically by JS -->
        <div class="card" style="padding: 1.25rem; text-align: center; background: rgba(0,0,0,0.02);">
            <div style="font-size: 0.85rem; color: var(--text-muted); font-weight: 600; text-transform: uppercase;">Loading Balances...</div>
        </div>
    </div>

    <!-- Reporting manager info -->
    <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>. All leave requests will be automatically routed to this supervisor.</span>
    </div>

    <!-- History -->
    <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 Leave 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;">Leave Type</th>
                        <th style="padding: 0.75rem 0.5rem;">Duration</th>
                        <th style="padding: 0.75rem 0.5rem;">Dates</th>
                        <th style="padding: 0.75rem 0.5rem;">Reason</th>
                        <th style="padding: 0.75rem 0.5rem;">Status</th>
                        <th style="padding: 0.75rem 0.5rem;">Approver Feedback</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($my_requests)): ?>
                        <tr>
                            <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 2rem;">No leave requests submitted 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; text-transform: capitalize;"><?php echo e($req['leave_type']); ?></td>
                                <td style="padding: 0.75rem 0.5rem;">
                                    <?php 
                                    if ($req['duration_type'] === 'full') {
                                        echo 'Full Day';
                                    } elseif ($req['duration_type'] === 'half_day') {
                                        echo 'Half Day (' . ucwords(str_replace('_', ' ', $req['half_day_type'])) . ')';
                                    } else {
                                        echo 'Short Leave (' . date('h:i A', strtotime($req['short_leave_start'])) . ' - ' . date('h:i A', strtotime($req['short_leave_end'])) . ')';
                                    }
                                    ?>
                                </td>
                                <td style="padding: 0.75rem 0.5rem; font-weight: 600;">
                                    <?php 
                                    if ($req['start_date'] === $req['end_date']) {
                                        echo $req['start_date'];
                                    } else {
                                        echo $req['start_date'] . ' to ' . $req['end_date'];
                                    }
                                    ?>
                                </td>
                                <td style="padding: 0.75rem 0.5rem; color: var(--text-muted);"><?php echo e($req['reason']); ?></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 if ($req['status'] !== 'pending'): ?>
                                        <strong><?php echo e($req['manager_name']); ?>:</strong> <?php echo e($req['action_reason'] ?: 'No comment'); ?>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- TAB 2: APPROVALS QUEUE (MANAGER ONLY) -->
<?php if ($is_mgr): ?>
<div id="approvals-tab" class="tab-content <?php echo hasRole('owner') ? 'active-content' : ''; ?>" <?php echo hasRole('owner') ? '' : '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-list-check" style="color: var(--primary); margin-right: 0.5rem;"></i> Pending Leave 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;">Leave Type</th>
                        <th style="padding: 0.75rem 0.5rem;">Duration</th>
                        <th style="padding: 0.75rem 0.5rem;">Dates</th>
                        <th style="padding: 0.75rem 0.5rem;">Reason</th>
                        <th style="padding: 0.75rem 0.5rem; text-align: right;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($pending_requests)): ?>
                        <tr>
                            <td colspan="7" style="text-align: center; color: var(--text-muted); padding: 2rem;">No pending leave requests in your queue.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($pending_requests 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; text-transform: capitalize;"><?php echo e($req['leave_type']); ?></td>
                                <td style="padding: 0.75rem 0.5rem;">
                                    <?php 
                                    if ($req['duration_type'] === 'full') {
                                        echo 'Full Day';
                                    } elseif ($req['duration_type'] === 'half_day') {
                                        echo 'Half Day (' . ucwords(str_replace('_', ' ', $req['half_day_type'])) . ')';
                                    } else {
                                        echo 'Short Leave (' . date('h:i A', strtotime($req['short_leave_start'])) . ' - ' . date('h:i A', strtotime($req['short_leave_end'])) . ')';
                                    }
                                    ?>
                                </td>
                                <td style="padding: 0.75rem 0.5rem; font-weight: 600;">
                                    <?php 
                                    if ($req['start_date'] === $req['end_date']) {
                                        echo $req['start_date'];
                                    } else {
                                        echo $req['start_date'] . ' to ' . $req['end_date'];
                                    }
                                    ?>
                                </td>
                                <td style="padding: 0.75rem 0.5rem; color: var(--text-muted);"><?php echo e($req['reason']); ?></td>
                                <td style="padding: 0.75rem 0.5rem; text-align: right;">
                                    <div style="display: inline-flex; gap: 0.5rem;">
                                        <button class="btn" style="background: rgba(16, 185, 129, 0.1); color: #10B981;" onclick="actionLeaveRequest(<?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;" onclick="actionLeaveRequest(<?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>

<!-- TAB 3: CONFIGURATIONS (MANAGER ONLY) -->
<div id="leave-config-tab" class="tab-content" style="display: none;">
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; align-items: start;">
        
        <!-- Leave Quota configurations -->
        <div class="card" style="padding: 1.5rem;">
            <h3 style="margin-top: 0; margin-bottom: 1.5rem; font-size: 1.1rem;"><i class="fas fa-cog" style="color: var(--primary); margin-right: 0.5rem;"></i> Annual Leave Entitlements</h3>
            <form id="leaveConfigForm" onsubmit="saveLeaveConfig(event)">
                <div class="form-group">
                    <label class="form-label">Casual Leaves (Days/Year)</label>
                    <input type="number" name="casual" class="form-control" value="<?php echo $limits['casual']; ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Annual Leaves (Days/Year)</label>
                    <input type="number" name="annual" class="form-control" value="<?php echo $limits['annual']; ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Sick Leaves (Days/Year)</label>
                    <input type="number" name="sick" class="form-control" value="<?php echo $limits['sick']; ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Maternity Leaves (Days/Year)</label>
                    <input type="number" name="maternity" class="form-control" value="<?php echo $limits['maternity']; ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Paternity Leaves (Days/Year)</label>
                    <input type="number" name="paternity" class="form-control" value="<?php echo $limits['paternity']; ?>" required>
                </div>
                
                <button type="submit" class="btn" style="background: var(--primary); color: white; width: 100%; margin-top: 1rem;">
                    Save Quotas
                </button>
            </form>
        </div>

        <!-- Public Holidays calendar list -->
        <div class="card" style="padding: 1.5rem;">
            <h3 style="margin-top: 0; margin-bottom: 1rem; font-size: 1.1rem;"><i class="fas fa-calendar" style="color: var(--primary); margin-right: 0.5rem;"></i> Public Holidays</h3>
            
            <form id="holidayForm" onsubmit="addHoliday(event)" style="display: flex; gap: 0.5rem; margin-bottom: 1.5rem;">
                <input type="date" name="holiday_date" class="form-control" required style="flex: 1;">
                <input type="text" name="holiday_name" class="form-control" placeholder="Holiday Name" required style="flex: 1.5;">
                <button type="submit" class="btn" style="background: var(--primary); color: white;">Add</button>
            </form>

            <div class="table-container" style="overflow-y: auto; max-height: 350px;">
                <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.5rem;">Date</th>
                            <th style="padding: 0.5rem;">Holiday</th>
                            <th style="padding: 0.5rem; text-align: right;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($holidays)): ?>
                            <tr>
                                <td colspan="3" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">No holidays added yet.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($holidays as $h): ?>
                                <tr style="border-bottom: 1px solid var(--border);">
                                    <td style="padding: 0.5rem; font-weight: 600;"><?php echo e($h['holiday_date']); ?></td>
                                    <td style="padding: 0.5rem;"><?php echo e($h['name']); ?></td>
                                    <td style="padding: 0.5rem; text-align: right;">
                                        <button class="btn btn-icon" style="background: rgba(239, 68, 68, 0.1); color: var(--danger);" onclick="deleteHoliday(<?php echo $h['id']; ?>)">
                                            <i class="fas fa-trash-can" style="font-size: 0.85rem;"></i>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<!-- TAB 4: COMPANY LEAVE RECORDS (MANAGER ONLY) -->
<div id="company-records-tab" class="tab-content" style="display: none;">
    <!-- Search and Date Filters -->
    <div class="card" style="padding: 1.25rem; margin-bottom: 1.5rem;">
        <form id="companyRecordsFilterForm" onsubmit="loadCompanyLeaveRecords(event)" data-no-busy style="display: flex; gap: 1rem; align-items: flex-end; flex-wrap: wrap; width: 100%;">
            <div class="form-group" style="margin-bottom: 0; flex: 2; min-width: 200px;">
                <label class="form-label" style="font-size: 0.75rem; display: block; margin-bottom: 0.35rem;">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="recordSearch" class="form-control" placeholder="Search by name or ID..." style="padding-left: 2.25rem; width: 100%;">
                </div>
            </div>
            <div class="form-group" style="margin-bottom: 0; flex: 1; min-width: 150px;">
                <label class="form-label" style="font-size: 0.75rem; display: block; margin-bottom: 0.35rem;">From Date</label>
                <input type="date" id="recordFromDate" class="form-control" style="width: 100%;">
            </div>
            <div class="form-group" style="margin-bottom: 0; flex: 1; min-width: 150px;">
                <label class="form-label" style="font-size: 0.75rem; display: block; margin-bottom: 0.35rem;">To Date</label>
                <input type="date" id="recordToDate" class="form-control" style="width: 100%;">
            </div>
            <div style="display: flex; gap: 0.5rem; margin-bottom: 0;">
                <button type="submit" class="btn" style="background: var(--primary); color: white; white-space: nowrap; height: 38px;">
                    <i class="fas fa-filter" style="margin-right: 0.35rem;"></i> Filter
                </button>
                <button type="button" class="btn" style="background: rgba(0,0,0,0.05); white-space: nowrap; height: 38px;" onclick="resetCompanyRecordsFilter()">
                    Clear
                </button>
            </div>
        </form>
    </div>

    <!-- Company Records Container -->
    <div id="companyRecordsContainer">
        <!-- Loaded dynamically by JS -->
        <div style="text-align: center; padding: 3rem; color: var(--text-muted);">
            <i class="fas fa-spinner fa-spin" style="font-size: 2rem; margin-bottom: 1rem; color: var(--primary);"></i>
            <p>Loading company leave records...</p>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Apply Leave Modal -->
<div id="applyLeaveModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h2 style="margin: 0; font-size: 1.25rem;">Apply for Time Off</h2>
            <button class="btn btn-icon" onclick="closeModal('applyLeaveModal')"><i class="fas fa-times"></i></button>
        </div>
        <form id="applyLeaveForm" onsubmit="submitLeaveRequest(event)">
            <div class="modal-body" style="display: flex; flex-direction: column; gap: 1.25rem; padding: 1.5rem;">
                <div class="form-group" style="margin-bottom: 0;">
                    <label class="form-label" style="font-weight: 600; margin-bottom: 0.5rem; display: block; color: var(--text-main);">Leave Type <span class="required-mark">*</span></label>
                    <select id="leave_type" name="leave_type" class="form-control" required>
                        <option value="casual">Casual Leave</option>
                        <option value="annual">Annual Leave</option>
                        <option value="sick">Sick Leave</option>
                        <option value="maternity">Maternity Leave</option>
                        <option value="paternity">Paternity Leave</option>
                        <option value="unpaid">Unpaid Day Off</option>
                    </select>
                </div>

                <div class="form-group" style="margin-bottom: 0;">
                    <label class="form-label" style="font-weight: 600; margin-bottom: 0.5rem; display: block; color: var(--text-main);">Duration Type <span class="required-mark">*</span></label>
                    <select id="duration_type" name="duration_type" class="form-control" required onchange="toggleDurationFields()">
                        <option value="full">Full Day(s)</option>
                        <option value="half_day">Half Day</option>
                        <option value="short_leave">Short Leave (Max 2 hours)</option>
                    </select>
                </div>

                <div class="form-group" style="margin-bottom: 0;">
                    <label class="form-label" id="dateLabel" style="font-weight: 600; margin-bottom: 0.5rem; display: block; color: var(--text-main);">Start Date <span class="required-mark">*</span></label>
                    <input type="date" id="start_date" name="start_date" class="form-control" required min="<?php echo date('Y-m-d'); ?>">
                </div>

                <div class="form-group" id="endDateGroup" style="margin-bottom: 0;">
                    <label class="form-label" style="font-weight: 600; margin-bottom: 0.5rem; display: block; color: var(--text-main);">End Date <span class="required-mark">*</span></label>
                    <input type="date" id="end_date" name="end_date" class="form-control" required min="<?php echo date('Y-m-d'); ?>">
                </div>

                <div class="form-group" id="halfDayGroup" style="display: none; margin-bottom: 0;">
                    <label class="form-label" style="font-weight: 600; margin-bottom: 0.5rem; display: block; color: var(--text-main);">Half Day Option <span class="required-mark">*</span></label>
                    <select id="half_day_type" name="half_day_type" class="form-control">
                        <option value="first_half">First Half (Morning)</option>
                        <option value="second_half">Second Half (Afternoon)</option>
                    </select>
                </div>

                <div id="shortLeaveGroup" style="display: none; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="font-weight: 600; margin-bottom: 0.5rem; display: block; color: var(--text-main);">Start Time <span class="required-mark">*</span></label>
                        <input type="time" id="short_leave_start" name="short_leave_start" class="form-control">
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label" style="font-weight: 600; margin-bottom: 0.5rem; display: block; color: var(--text-main);">End Time <span class="required-mark">*</span></label>
                        <input type="time" id="short_leave_end" name="short_leave_end" class="form-control">
                    </div>
                </div>

                <div class="form-group" style="margin-bottom: 0;">
                    <label class="form-label" style="font-weight: 600; margin-bottom: 0.5rem; display: block; color: var(--text-main);">Reason for Request <span class="required-mark">*</span></label>
                    <textarea id="reason" name="reason" class="form-control" style="height: 100px;" placeholder="Brief details about your leave..." required></textarea>
                </div>
            </div>

            <div class="modal-footer" style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 0;">
                <button type="button" class="btn" style="background: rgba(0,0,0,0.05);" onclick="closeModal('applyLeaveModal')">Cancel</button>
                <button type="submit" class="btn" style="background: var(--primary); color: white;">Submit Request</button>
            </div>
        </form>
    </div>
</div>

<!-- Approval comment Modal -->
<div id="approvalModal" class="modal-overlay">
    <div class="modal-content" style="max-width: 400px; text-align: center; padding: 2rem;">
        <h2 id="approvalTitle" style="margin-bottom: 0.5rem;">Leave Action</h2>
        <p id="approvalMessage" style="color: var(--text-muted); margin-bottom: 1.5rem;">Provide optional comments for this decision.</p>
        
        <input type="hidden" id="action_req_id">
        <input type="hidden" id="action_status">
        <textarea id="action_comment" class="form-control" placeholder="Approver comment..." style="height: 80px; margin-bottom: 1.5rem;"></textarea>

        <div style="display: flex; gap: 1rem; justify-content: center;">
            <button class="btn" style="background: rgba(0,0,0,0.05); min-width: 100px;" onclick="closeModal('approvalModal')">Cancel</button>
            <button id="btnSubmitApproval" class="btn" style="background: var(--primary); color: white; min-width: 100px;" onclick="submitLeaveAction()">Submit</button>
        </div>
    </div>
</div>

<script>
// 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');
    
    if (tabId === 'company-records-tab') {
        loadCompanyLeaveRecords();
    }
}

// Company Leave Records Tab Functions
async function loadCompanyLeaveRecords(e = null) {
    if (e) e.preventDefault();
    
    const container = document.getElementById('companyRecordsContainer');
    if (!container) return;
    
    const search = document.getElementById('recordSearch').value;
    const startDate = document.getElementById('recordFromDate').value;
    const endDate = document.getElementById('recordToDate').value;
    
    // Show spinner
    container.innerHTML = `
        <div style="text-align: center; padding: 3rem; color: var(--text-muted);">
            <i class="fas fa-spinner fa-spin" style="font-size: 2rem; margin-bottom: 1rem; color: var(--primary);"></i>
            <p>Loading company leave records...</p>
        </div>
    `;
    
    const res = await apiCall('leaves', {
        action: 'company_records',
        search: search,
        start_date: startDate,
        end_date: endDate
    });
    
    if (res.success) {
        if (res.records.length === 0) {
            container.innerHTML = `
                <div class="card" style="padding: 3rem; text-align: center; color: var(--text-muted);">
                    <i class="fas fa-folder-open" style="font-size: 3rem; margin-bottom: 1rem; color: var(--text-muted); opacity: 0.5;"></i>
                    <p style="font-size: 1.1rem; font-weight: 600; margin: 0;">No Employee Records Found</p>
                    <p style="font-size: 0.9rem; margin-top: 0.25rem;">Try adjusting your filters or search query.</p>
                </div>
            `;
            return;
        }
        
        let tableRowsHtml = '';
        res.records.forEach(rec => {
            const historyCount = rec.history.length;
            const rowspan = historyCount > 0 ? historyCount : 1;
            
            // Generate row starting with Rowspan fields (Employee name and leave type balances)
            tableRowsHtml += `
                <tr style="border-bottom: 1px solid var(--border);">
                    <!-- Employee Info (Rowspan) -->
                    <td rowspan="${rowspan}" style="padding: 0.75rem 0.5rem; vertical-align: top; border-right: 1px solid var(--border); font-weight: 600;">
                        <div style="font-weight: 700; color: var(--text-color);">${escapeHtml(rec.employee_name)}</div>
                        <div style="font-family: monospace; font-size: 0.75rem; color: var(--text-muted); font-weight: 700; margin-top: 0.15rem;">${rec.employee_code}</div>
                    </td>
                    <!-- Leave Balances (Rowspan) -->
                    <td rowspan="${rowspan}" style="padding: 0.75rem 0.5rem; text-align: center; vertical-align: top; border-right: 1px solid var(--border);">
                        <span style="font-weight: 700; color: var(--text-color);">${rec.balances.casual.remaining}</span><span style="font-size: 0.75rem; color: var(--text-muted);">/${rec.balances.casual.limit}</span>
                    </td>
                    <td rowspan="${rowspan}" style="padding: 0.75rem 0.5rem; text-align: center; vertical-align: top; border-right: 1px solid var(--border);">
                        <span style="font-weight: 700; color: var(--text-color);">${rec.balances.annual.remaining}</span><span style="font-size: 0.75rem; color: var(--text-muted);">/${rec.balances.annual.limit}</span>
                    </td>
                    <td rowspan="${rowspan}" style="padding: 0.75rem 0.5rem; text-align: center; vertical-align: top; border-right: 1px solid var(--border);">
                        <span style="font-weight: 700; color: var(--text-color);">${rec.balances.sick.remaining}</span><span style="font-size: 0.75rem; color: var(--text-muted);">/${rec.balances.sick.limit}</span>
                    </td>
                    <td rowspan="${rowspan}" style="padding: 0.75rem 0.5rem; text-align: center; vertical-align: top; border-right: 1px solid var(--border);">
                        <span style="font-weight: 700; color: var(--text-color);">${rec.balances.maternity.remaining}</span><span style="font-size: 0.75rem; color: var(--text-muted);">/${rec.balances.maternity.limit}</span>
                    </td>
                    <td rowspan="${rowspan}" style="padding: 0.75rem 0.5rem; text-align: center; vertical-align: top; border-right: 1px solid var(--border);">
                        <span style="font-weight: 700; color: var(--text-color);">${rec.balances.paternity.remaining}</span><span style="font-size: 0.75rem; color: var(--text-muted);">/${rec.balances.paternity.limit}</span>
                    </td>
            `;
            
            if (historyCount === 0) {
                tableRowsHtml += `
                    <td colspan="5" style="padding: 0.75rem 0.5rem; text-align: center; color: var(--text-muted); font-style: italic;">No leave history found for this period.</td>
                </tr>
                `;
            } else {
                // First request row details
                const first = rec.history[0];
                tableRowsHtml += `
                    <td style="padding: 0.75rem 0.5rem; font-weight: 600;">
                        ${first.start_date === first.end_date ? first.start_date : `${first.start_date} to ${first.end_date}`}
                    </td>
                    <td style="padding: 0.75rem 0.5rem; text-transform: capitalize;">${first.leave_type}</td>
                    <td style="padding: 0.75rem 0.5rem;">${getDurationStr(first)}</td>
                    <td style="padding: 0.75rem 0.5rem; color: var(--text-muted); max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml(first.reason)}">${escapeHtml(first.reason)}</td>
                    <td style="padding: 0.75rem 0.5rem;">
                        ${getStatusBadge(first.status)}
                    </td>
                </tr>
                `;
                
                // Subsequent rows
                for (let i = 1; i < historyCount; i++) {
                    const h = rec.history[i];
                    tableRowsHtml += `
                        <tr style="border-bottom: 1px solid var(--border);">
                            <td style="padding: 0.75rem 0.5rem; font-weight: 600;">
                                ${h.start_date === h.end_date ? h.start_date : `${h.start_date} to ${h.end_date}`}
                            </td>
                            <td style="padding: 0.75rem 0.5rem; text-transform: capitalize;">${h.leave_type}</td>
                            <td style="padding: 0.75rem 0.5rem;">${getDurationStr(h)}</td>
                            <td style="padding: 0.75rem 0.5rem; color: var(--text-muted); max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml(h.reason)}">${escapeHtml(h.reason)}</td>
                            <td style="padding: 0.75rem 0.5rem;">
                                ${getStatusBadge(h.status)}
                            </td>
                        </tr>
                    `;
                }
            }
        });
        
        container.innerHTML = `
            <div class="card" style="padding: 1.5rem;">
                <div class="table-container" style="overflow-x: auto;">
                    <table class="table" style="width: 100%; border-collapse: collapse; min-width: 1000px; font-size: 0.9rem;">
                        <thead>
                            <tr style="border-bottom: 2px solid var(--border); text-align: left; background: rgba(124, 58, 237, 0.02); font-size: 0.8rem; text-transform: uppercase; color: var(--text-muted);">
                                <th style="padding: 0.75rem 0.5rem; border-right: 1px solid var(--border);">Employee</th>
                                <th style="padding: 0.75rem 0.5rem; text-align: center; border-right: 1px solid var(--border);">Casual Bal.</th>
                                <th style="padding: 0.75rem 0.5rem; text-align: center; border-right: 1px solid var(--border);">Annual Bal.</th>
                                <th style="padding: 0.75rem 0.5rem; text-align: center; border-right: 1px solid var(--border);">Sick Bal.</th>
                                <th style="padding: 0.75rem 0.5rem; text-align: center; border-right: 1px solid var(--border);">Maternity Bal.</th>
                                <th style="padding: 0.75rem 0.5rem; text-align: center; border-right: 1px solid var(--border);">Paternity Bal.</th>
                                <th style="padding: 0.75rem 0.5rem;">Dates Taken</th>
                                <th style="padding: 0.75rem 0.5rem;">Leave Type</th>
                                <th style="padding: 0.75rem 0.5rem;">Duration</th>
                                <th style="padding: 0.75rem 0.5rem;">Reason</th>
                                <th style="padding: 0.75rem 0.5rem;">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${tableRowsHtml}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
    } else {
        notify(res.message || 'Failed to load records', 'error');
    }
}

function getStatusBadge(status) {
    let badgeBg = 'rgba(0,0,0,0.05)';
    let badgeFg = 'var(--text-muted)';
    if (status === 'approved') {
        badgeBg = 'rgba(16, 185, 129, 0.1)';
        badgeFg = '#10B981';
    } else if (status === 'rejected') {
        badgeBg = 'rgba(239, 68, 68, 0.1)';
        badgeFg = '#EF4444';
    } else if (status === 'pending') {
        badgeBg = 'rgba(245, 158, 11, 0.1)';
        badgeFg = '#F59E0B';
    }
    return `
        <span class="badge" style="background: ${badgeBg}; color: ${badgeFg}; padding: 0.2rem 0.4rem; border-radius: 5px; font-size: 0.75rem; text-transform: uppercase; font-weight: 600;">
            ${status}
        </span>
    `;
}

function getDurationStr(h) {
    if (h.duration_type === 'full') {
        return `${h.duration_days} Day(s) (Full)`;
    } else if (h.duration_type === 'half_day') {
        return `0.5 Day (Half)`;
    } else {
        return `Short Leave (0.25 Day)`;
    }
}

function resetCompanyRecordsFilter() {
    document.getElementById('recordSearch').value = '';
    document.getElementById('recordFromDate').value = '';
    document.getElementById('recordToDate').value = '';
    loadCompanyLeaveRecords();
}

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

// Modal and duration fields handling
function openApplyLeaveModal() {
    document.getElementById('applyLeaveForm').reset();
    toggleDurationFields();
    openModal('applyLeaveModal');
}

function toggleDurationFields() {
    const durType = document.getElementById('duration_type').value;
    const endDateGroup = document.getElementById('endDateGroup');
    const halfDayGroup = document.getElementById('halfDayGroup');
    const shortLeaveGroup = document.getElementById('shortLeaveGroup');
    const dateLabel = document.getElementById('dateLabel');
    
    // reset required values
    document.getElementById('end_date').required = false;
    document.getElementById('half_day_type').required = false;
    document.getElementById('short_leave_start').required = false;
    document.getElementById('short_leave_end').required = false;

    if (durType === 'full') {
        dateLabel.innerText = "Start Date *";
        endDateGroup.style.display = 'block';
        document.getElementById('end_date').required = true;
        
        halfDayGroup.style.display = 'none';
        shortLeaveGroup.style.display = 'none';
    } else if (durType === 'half_day') {
        dateLabel.innerText = "Date *";
        endDateGroup.style.display = 'none';
        
        halfDayGroup.style.display = 'block';
        document.getElementById('half_day_type').required = true;
        
        shortLeaveGroup.style.display = 'none';
    } else if (durType === 'short_leave') {
        dateLabel.innerText = "Date *";
        endDateGroup.style.display = 'none';
        halfDayGroup.style.display = 'none';
        
        shortLeaveGroup.style.display = 'grid';
        document.getElementById('short_leave_start').required = true;
        document.getElementById('short_leave_end').required = true;
    }
}

// Fetch balances
async function loadLeaveBalances() {
    const row = document.getElementById('leaveBalancesRow');
    if (!row) return;
    const res = await apiCall('leaves', { action: 'balances' });
    if (res.success) {
        row.innerHTML = '';
        
        Object.entries(res.balances).forEach(([type, bal]) => {
            const pct = bal.limit > 0 ? Math.round((bal.taken / bal.limit) * 100) : 0;
            const remaining = bal.remaining;
            
            const card = document.createElement('div');
            card.className = 'card';
            card.style.padding = '1.25rem';
            card.style.textAlign = 'center';
            card.style.display = 'flex';
            card.style.flexDirection = 'column';
            card.style.alignItems = 'center';
            card.style.justifyContent = 'center';
            card.style.gap = '0.5rem';
            
            // Nice circular rings or progress bars
            card.innerHTML = `
                <div style="font-size: 0.75rem; text-transform: uppercase; color: var(--text-muted); font-weight: 700; letter-spacing: 0.5px;">${type} Leave</div>
                <div style="font-size: 1.5rem; font-weight: 800; color: var(--text-color); margin: 0.25rem 0;">${remaining} <span style="font-size: 0.85rem; color: var(--text-muted); font-weight: 500;">/ ${bal.limit} Left</span></div>
                <div style="width: 100%; height: 5px; background: rgba(0,0,0,0.05); border-radius: 10px; overflow: hidden;">
                    <div style="width: ${100 - pct}%; height: 100%; background: var(--primary); border-radius: 10px;"></div>
                </div>
            `;
            
            row.appendChild(card);
        });
    }
}

// Form Submission
async function submitLeaveRequest(e) {
    e.preventDefault();
    const form = document.getElementById('applyLeaveForm');
    const formData = new FormData(form);
    
    // Construct request data
    const data = {
        action: 'apply',
        leave_type: formData.get('leave_type'),
        duration_type: formData.get('duration_type'),
        start_date: formData.get('start_date'),
        end_date: formData.get('end_date'),
        half_day_type: formData.get('half_day_type'),
        short_leave_start: formData.get('short_leave_start'),
        short_leave_end: formData.get('short_leave_end'),
        reason: formData.get('reason')
    };
    
    const submitBtn = form.querySelector('button[type="submit"]');
    setLoading(submitBtn, true);
    const res = await apiCall('leaves', data);
    setLoading(submitBtn, false);
    
    if (res.success) {
        notify(res.message, 'success');
        closeModal('applyLeaveModal');
        setTimeout(() => window.location.reload(), 1000);
    } else {
        notify(res.message, 'error');
    }
}

// Manager approvals
function actionLeaveRequest(id, status) {
    document.getElementById('action_req_id').value = id;
    document.getElementById('action_status').value = status;
    document.getElementById('action_comment').value = '';
    
    const title = status === 'approved' ? 'Approve Leave' : 'Reject Leave';
    const msg = status === 'approved' ? 'Are you sure you want to approve this leave?' : 'Are you sure you want to reject this leave?';
    const btn = document.getElementById('btnSubmitApproval');
    
    document.getElementById('approvalTitle').innerText = title;
    document.getElementById('approvalMessage').innerText = msg;
    
    btn.style.background = status === 'approved' ? '#10B981' : '#EF4444';
    btn.innerText = status === 'approved' ? 'Approve' : 'Reject';
    
    openModal('approvalModal');
}

async function submitLeaveAction() {
    const id = document.getElementById('action_req_id').value;
    const status = document.getElementById('action_status').value;
    const comment = document.getElementById('action_comment').value;
    
    const btn = document.getElementById('btnSubmitApproval');
    setLoading(btn, true);
    
    const res = await apiCall('leaves', {
        action: 'action_request',
        id: id,
        status: status,
        comment: comment
    });
    setLoading(btn, false);
    
    if (res.success) {
        notify(res.message, 'success');
        closeModal('approvalModal');
        setTimeout(() => window.location.reload(), 1000);
    } else {
        notify(res.message, 'error');
    }
}

// Configurations
async function saveLeaveConfig(e) {
    e.preventDefault();
    const form = document.getElementById('leaveConfigForm');
    const formData = new FormData(form);
    
    const config = {
        casual: formData.get('casual'),
        annual: formData.get('annual'),
        sick: formData.get('sick'),
        maternity: formData.get('maternity'),
        paternity: formData.get('paternity')
    };
    
    const submitBtn = form.querySelector('button[type="submit"]');
    setLoading(submitBtn, true);
    
    const res = await apiCall('leaves', { action: 'save_config', config: config });
    setLoading(submitBtn, false);
    
    if (res.success) {
        notify(res.message, 'success');
    } else {
        notify(res.message, 'error');
    }
}

async function addHoliday(e) {
    e.preventDefault();
    const form = document.getElementById('holidayForm');
    const formData = new FormData(form);
    
    const submitBtn = form.querySelector('button[type="submit"]');
    setLoading(submitBtn, true);
    
    const res = await apiCall('leaves', {
        action: 'add_holiday',
        holiday_date: formData.get('holiday_date'),
        holiday_name: formData.get('holiday_name')
    });
    setLoading(submitBtn, false);
    
    if (res.success) {
        notify(res.message, 'success');
        setTimeout(() => window.location.reload(), 1000);
    } else {
        notify(res.message, 'error');
    }
}

async function deleteHoliday(id) {
    const proceed = await confirmAction({
        title: 'Delete Public Holiday',
        message: 'Are you sure you want to remove this public holiday from the calendar?',
        confirmText: 'Delete'
    });
    
    if (proceed) {
        const res = await apiCall('leaves', { action: 'delete_holiday', id: id });
        if (res.success) {
            notify(res.message, 'success');
            setTimeout(() => window.location.reload(), 1000);
        } else {
            notify(res.message, 'error');
        }
    }
}

// Initialise
document.addEventListener('DOMContentLoaded', () => {
    loadLeaveBalances();
});
</script>
