<?php
/**
 * Enterprise HRM ERP System - Resigned & Abscondee Report
 * Month and Year wise report viewing with search functionality
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$pageTitle = 'Resigned & Abscondee Report';
$currentModule = 'exit';

$siteId = getCurrentSiteId();
$selectedMonth = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$selectedYear = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
$searchQuery = isset($_GET['search']) ? trim($_GET['search']) : '';

// Validate
if ($selectedMonth < 1 || $selectedMonth > 12) $selectedMonth = (int)date('m');
if ($selectedYear < 2020 || $selectedYear > 2100) $selectedYear = (int)date('Y');

$entries = [];

try {
    $db = getDB();
    
    // Build query
    $whereConditions = ["ra.site_id = ?"];
    $params = [$siteId];
    
    // Month/Year filter
    $monthYear = date('M-Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear));
    $whereConditions[] = "ra.month = ?";
    $params[] = $monthYear;
    
    // Search filter
    if (!empty($searchQuery)) {
        $whereConditions[] = "(ra.emp_id LIKE ? OR ra.name LIKE ?)";
        $searchParam = "%{$searchQuery}%";
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    $whereClause = implode(' AND ', $whereConditions);
    
    $stmt = $db->prepare("
        SELECT ra.*, e.employee_code as actual_emp_code
        FROM resigned_abscondee ra
        LEFT JOIN employees e ON ra.employee_id = e.employee_id
        WHERE {$whereClause}
        ORDER BY ra.sl_no ASC, ra.exit_id ASC
    ");
    $stmt->execute($params);
    $entries = $stmt->fetchAll();
    
    // Get site name
    $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
    $stmt->execute([$siteId]);
    $site = $stmt->fetch();
    $siteName = $site['site_name'] ?? '';
    
} catch (Exception $e) {
    error_log("Error loading report: " . $e->getMessage());
    $entries = [];
    $siteName = '';
}

include __DIR__ . '/../../includes/header.php';
include __DIR__ . '/../payroll/_navigation.php';
?>

<style>
.report-container {
    padding: 20px;
    background: #f5f5f5;
}

.filter-section {
    background: white;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
}

.filter-section label {
    font-weight: bold;
    margin-right: 5px;
}

.filter-section select,
.filter-section input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.search-box {
    flex: 1;
    min-width: 200px;
}

.search-box input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.btn-filter {
    background: #3b82f6;
    color: white;
    padding: 8px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.btn-filter:hover {
    background: #1e293b;
}

.btn-clear {
    background: #6b7280;
    color: white;
    padding: 8px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-clear:hover {
    background: #4b5563;
}

.report-table-container {
    background: white;
    padding: 20px;
    border-radius: 8px;
    overflow-x: auto;
}

.report-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}

.report-table th {
    background: #1e40af;
    color: white;
    padding: 12px 8px;
    text-align: center;
    font-weight: bold;
    border: 1px solid #1e3a8a;
    white-space: nowrap;
    position: sticky;
    top: 0;
    z-index: 10;
}

.report-table td {
    padding: 10px 8px;
    border: 1px solid #d1d5db;
    background: white;
    text-align: center;
}

.report-table tbody tr:hover {
    background: #f0f9ff;
}

.report-table .text-left {
    text-align: left;
}

.report-header {
    background: #f0f9ff;
    padding: 15px;
    margin-bottom: 20px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 15px;
}

.report-header .site-name {
    background: #d1fae5;
    padding: 10px 20px;
    border-radius: 4px;
    font-weight: bold;
    font-size: 16px;
}

.report-header .month-year {
    background: #fef3c7;
    padding: 10px 20px;
    border-radius: 4px;
    font-weight: bold;
    font-size: 16px;
}

.report-header .count {
    background: #dbeafe;
    padding: 10px 20px;
    border-radius: 4px;
    font-weight: bold;
}

.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: bold;
}

.status-resigned {
    background: #dbeafe;
    color: #1e40af;
}

.status-abscondee {
    background: #fee2e2;
    color: #991b1b;
}

.no-data {
    text-align: center;
    padding: 40px;
    color: #6b7280;
}

.no-data-icon {
    font-size: 48px;
    margin-bottom: 10px;
}

.btn-export {
    background: #10b981;
    color: white;
    padding: 8px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-export:hover {
    background: #059669;
}

.btn-back {
    background: #6b7280;
    color: white;
    padding: 8px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}

.btn-back:hover {
    background: #4b5563;
}
</style>

<div class="report-container">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">Resigned & Abscondee Report</h2>
            <a href="<?php echo BASE_URL; ?>/modules/exit/resigned_abscondee.php" class="btn-back">← Back to Entry</a>
        </div>
        
        <div class="filter-section">
            <div>
                <label>Month:</label>
                <select id="filter_month" onchange="applyFilters()">
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?php echo $m; ?>" <?php echo $m == $selectedMonth ? 'selected' : ''; ?>>
                        <?php echo date('F', mktime(0, 0, 0, $m, 1)); ?>
                    </option>
                    <?php endfor; ?>
                </select>
            </div>
            
            <div>
                <label>Year:</label>
                <input type="number" id="filter_year" value="<?php echo $selectedYear; ?>" 
                       min="2020" max="2100" onchange="applyFilters()" style="width: 100px;">
            </div>
            
            <div class="search-box">
                <label>Search (Employee ID / Name):</label>
                <input type="text" id="search_input" value="<?php echo htmlspecialchars($searchQuery); ?>" 
                       placeholder="Enter Employee ID or Name..." 
                       onkeypress="if(event.key === 'Enter') applyFilters()">
            </div>
            
            <div style="display: flex; gap: 10px; align-items: flex-end;">
                <button onclick="applyFilters()" class="btn-filter">Apply Filters</button>
                <a href="<?php echo $_SERVER['PHP_SELF']; ?>?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" class="btn-clear">Clear Search</a>
            </div>
        </div>
        
        <div class="report-header">
            <div class="site-name">Site Name: <?php echo htmlspecialchars($siteName); ?></div>
            <div class="month-year"><?php echo date('M-Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?></div>
            <div class="count">Total Records: <?php echo count($entries); ?></div>
        </div>
        
        <?php if (count($entries) > 0): ?>
        <div class="report-table-container">
            <table class="report-table">
                <thead>
                    <tr>
                        <th>Sl No</th>
                        <th>Emp Id</th>
                        <th>Name</th>
                        <th>Designation</th>
                        <th>Category</th>
                        <th>Resigned/ Abscondee</th>
                        <th>Site Name</th>
                        <th>Location</th>
                        <th>Last Date of Working</th>
                        <th>Resignation Submitted</th>
                        <th>Notice Period served</th>
                        <th>Remarks</th>
                        <th style="width: 120px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($entries as $entry): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($entry['sl_no'] ?? ''); ?></td>
                        <td>
                            <strong><?php echo htmlspecialchars($entry['emp_id'] ?: ($entry['actual_emp_code'] ?? '')); ?></strong>
                        </td>
                        <td class="text-left">
                            <strong><?php echo htmlspecialchars($entry['name'] ?? ''); ?></strong>
                        </td>
                        <td><?php echo htmlspecialchars($entry['designation'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($entry['category'] ?? ''); ?></td>
                        <td>
                            <span class="status-badge status-<?php echo strtolower($entry['resigned_abscondee'] ?? 'resigned'); ?>">
                                <?php echo htmlspecialchars($entry['resigned_abscondee'] ?? 'Resigned'); ?>
                            </span>
                        </td>
                        <td><?php echo htmlspecialchars($entry['site_name'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($entry['location'] ?? ''); ?></td>
                        <td>
                            <?php if ($entry['last_date_of_working']): ?>
                                <?php echo date('d-M-Y', strtotime($entry['last_date_of_working'])); ?>
                            <?php else: ?>
                                <span style="color: #9ca3af;">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($entry['resignation_submitted']): ?>
                                <?php echo date('d-M-Y', strtotime($entry['resignation_submitted'])); ?>
                            <?php else: ?>
                                <span style="color: #9ca3af;">-</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($entry['notice_period_served'] ?? ''); ?></td>
                        <td class="text-left" style="max-width: 200px;">
                            <?php echo htmlspecialchars($entry['remark'] ?? ''); ?>
                        </td>
                        <td style="text-align: center;">
                            <a href="<?php echo BASE_URL; ?>/modules/exit/resigned_abscondee_edit.php?id=<?php echo $entry['exit_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                               class="btn btn-sm" style="background: #3b82f6; color: white; padding: 5px 10px; border: none; border-radius: 4px; text-decoration: none; display: inline-block; margin-right: 5px; font-size: 12px;">✏️ Edit</a>
                            <a href="<?php echo BASE_URL; ?>/modules/exit/resigned_abscondee_delete.php?id=<?php echo $entry['exit_id']; ?>&month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
                               class="btn btn-sm" style="background: #ef4444; color: white; padding: 5px 10px; border: none; border-radius: 4px; text-decoration: none; display: inline-block; font-size: 12px;"
                               onclick="return confirm('Are you sure you want to delete this record?');">🗑️ Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <div style="margin-top: 20px; text-align: right;">
            <a href="<?php echo BASE_URL; ?>/modules/exit/resigned_abscondee_export.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>&search=<?php echo urlencode($searchQuery); ?>" 
               class="btn-export">Export to Excel</a>
        </div>
        
        <?php else: ?>
        <div class="no-data">
            <div class="no-data-icon">📋</div>
            <h3>No Data Found</h3>
            <p>
                <?php if (!empty($searchQuery)): ?>
                    No records found for the search query "<?php echo htmlspecialchars($searchQuery); ?>" 
                    in <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>.
                <?php else: ?>
                    No records found for <?php echo date('F Y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear)); ?>.
                <?php endif; ?>
            </p>
            <a href="<?php echo BASE_URL; ?>/modules/exit/resigned_abscondee.php?month=<?php echo $selectedMonth; ?>&year=<?php echo $selectedYear; ?>" 
               class="btn-back" style="margin-top: 15px;">Add Data</a>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
function applyFilters() {
    const month = document.getElementById('filter_month').value;
    const year = document.getElementById('filter_year').value;
    const search = document.getElementById('search_input').value.trim();
    
    let url = '<?php echo $_SERVER['PHP_SELF']; ?>?month=' + month + '&year=' + year;
    if (search) {
        url += '&search=' + encodeURIComponent(search);
    }
    
    window.location.href = url;
}

</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

