<?php
session_start();
require_once 'config/database.php';
require_once 'config/session.php';

// Check permission
if(!isAdmin() && !isManager()) {
    echo "<div class='alert alert-danger'>Access Denied! Only Admins and Managers can access Reports.</div>";
    exit();
}

// Get filter parameters
$report_type = $_GET['type'] ?? 'attendance';
$month = $_GET['month'] ?? date('Y-m');
$department = $_GET['department'] ?? 'all';
$employee_id = $_GET['employee'] ?? 'all';
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');

// Get departments for filter
$dept_stmt = $pdo->query("SELECT DISTINCT department FROM employees WHERE department IS NOT NULL ORDER BY department");
$departments = $dept_stmt->fetchAll();

// Get employees for filter
$emp_stmt = $pdo->query("SELECT id, full_name, department FROM employees ORDER BY full_name");
$employees = $emp_stmt->fetchAll();

// Function to generate reports
function getAttendanceReport($pdo, $month, $department, $employee_id) {
    $params = [];
    $where = "WHERE a.attendance_date BETWEEN ? AND ?";
    $start = date('Y-m-01', strtotime($month));
    $end = date('Y-m-t', strtotime($month));
    $params[] = $start;
    $params[] = $end;
    
    if($department != 'all') {
        $where .= " AND e.department = ?";
        $params[] = $department;
    }
    
    if($employee_id != 'all') {
        $where .= " AND a.employee_id = ?";
        $params[] = $employee_id;
    }
    
    $query = "SELECT 
                e.full_name,
                e.department,
                COUNT(CASE WHEN a.status IN ('present', 'wfh', 'half-day') THEN 1 END) as present_days,
                COUNT(CASE WHEN a.status = 'absent' THEN 1 END) as absent_days,
                COUNT(CASE WHEN a.status = 'wfh' THEN 1 END) as wfh_days,
                COUNT(CASE WHEN a.status = 'half-day' THEN 1 END) as half_days,
                SUM(a.late_minutes) as total_late_minutes,
                SUM(a.early_leave_minutes) as total_early_minutes
              FROM attendance a
              JOIN employees e ON a.employee_id = e.id
              $where
              GROUP BY a.employee_id
              ORDER BY e.department, e.full_name";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function getLeaveReport($pdo, $start_date, $end_date, $department) {
    $params = [];
    $where = "WHERE l.start_date BETWEEN ? AND ?";
    $params[] = $start_date;
    $params[] = $end_date;
    
    if($department != 'all') {
        $where .= " AND e.department = ?";
        $params[] = $department;
    }
    
    $query = "SELECT 
                e.full_name,
                e.department,
                l.leave_type,
                COUNT(*) as total_leaves,
                SUM(l.total_days) as total_days,
                COUNT(CASE WHEN l.status = 'approved' THEN 1 END) as approved_leaves,
                COUNT(CASE WHEN l.status = 'pending' THEN 1 END) as pending_leaves,
                COUNT(CASE WHEN l.status = 'rejected' THEN 1 END) as rejected_leaves
              FROM leaves l
              JOIN employees e ON l.employee_id = e.id
              $where
              GROUP BY l.employee_id, l.leave_type
              ORDER BY e.department, e.full_name, l.leave_type";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function getSalaryReport($pdo, $month, $department) {
    $params = [];
    $where = "WHERE 1=1";
    
    if($department != 'all') {
        $where .= " AND department = ?";
        $params[] = $department;
    }
    
    $query = "SELECT 
                full_name,
                department,
                employment_type,
                salary,
                allowance,
                (salary + allowance) as total_salary,
                join_date
              FROM employees
              $where
              ORDER BY department, employment_type, salary DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

function getPerformanceReport($pdo) {
    $query = "SELECT 
                e.full_name,
                e.department,
                e.employment_type,
                COUNT(DISTINCT a.id) as attendance_count,
                COUNT(DISTINCT l.id) as leave_count,
                ROUND(AVG(CASE WHEN a.status = 'present' THEN 1 ELSE 0 END) * 100, 2) as attendance_percentage
              FROM employees e
              LEFT JOIN attendance a ON e.id = a.employee_id AND MONTH(a.attendance_date) = MONTH(CURDATE())
              LEFT JOIN leaves l ON e.id = l.employee_id AND l.status = 'approved' AND MONTH(l.start_date) = MONTH(CURDATE())
              GROUP BY e.id
              ORDER BY e.department, e.full_name";
    
    $stmt = $pdo->query($query);
    return $stmt->fetchAll();
}

// Generate report based on type
$report_data = [];
$report_title = "";

switch($report_type) {
    case 'attendance':
        $report_data = getAttendanceReport($pdo, $month, $department, $employee_id);
        $report_title = "Attendance Report - " . date('F Y', strtotime($month));
        break;
    case 'leave':
        $report_data = getLeaveReport($pdo, $start_date, $end_date, $department);
        $report_title = "Leave Report - " . date('d M Y', strtotime($start_date)) . " to " . date('d M Y', strtotime($end_date));
        break;
    case 'salary':
        $report_data = getSalaryReport($pdo, $month, $department);
        $report_title = "Salary Report - " . date('F Y', strtotime($month));
        break;
    case 'performance':
        $report_data = getPerformanceReport($pdo);
        $report_title = "Performance Overview";
        break;
}

// Handle export requests
if (isset($_GET['export'])) {
    $export_type = $_GET['export'];
    $filename = "HR_Report_" . $report_type . "_" . date('Y_m_d');
    
    if ($export_type == 'excel') {
        exportToExcel($report_data, $report_title, $filename);
    } elseif ($export_type == 'pdf') {
        exportToPDF($report_data, $report_title, $filename);
    }
    exit();
}

function exportToExcel($data, $title, $filename) {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="' . $filename . '.xls"');
    
    echo '<html><head>';
    echo '<style>td{border:1px solid #ddd; padding:5px;} th{background:#f5f5f5; border:1px solid #ddd; padding:5px;}</style>';
    echo '</head><body>';
    echo '<h2>' . $title . '</h2>';
    echo '<h4>Generated on: ' . date('Y-m-d H:i:s') . '</h4>';
    echo '<table border="1">';
    
    if (count($data) > 0) {
        // Headers
        echo '<tr>';
        foreach ($data[0] as $key => $value) {
            if (!is_numeric($key)) {
                echo '<th>' . ucwords(str_replace('_', ' ', $key)) . '</th>';
            }
        }
        echo '</tr>';
        
        // Data
        foreach ($data as $row) {
            echo '<tr>';
            foreach ($row as $key => $value) {
                if (!is_numeric($key)) {
                    echo '<td>' . htmlspecialchars($value) . '</td>';
                }
            }
            echo '</tr>';
        }
    }
    
    echo '</table>';
    echo '</body></html>';
    exit();
}

function exportToPDF($data, $title, $filename) {
    require_once('vendor/autoload.php'); // Require TCPDF library
    
    $pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetCreator('HR System');
    $pdf->SetAuthor('HR System');
    $pdf->SetTitle($title);
    $pdf->SetSubject('HR Report');
    
    $pdf->AddPage();
    $pdf->SetFont('helvetica', '', 10);
    
    // Title
    $pdf->SetFont('helvetica', 'B', 16);
    $pdf->Cell(0, 10, $title, 0, 1, 'C');
    $pdf->SetFont('helvetica', '', 10);
    $pdf->Cell(0, 10, 'Generated on: ' . date('Y-m-d H:i:s'), 0, 1, 'C');
    $pdf->Ln(10);
    
    // Table
    if (count($data) > 0) {
        $html = '<table border="1" cellpadding="4">';
        
        // Headers
        $html .= '<tr style="background-color:#f2f2f2;">';
        foreach ($data[0] as $key => $value) {
            if (!is_numeric($key)) {
                $html .= '<th>' . ucwords(str_replace('_', ' ', $key)) . '</th>';
            }
        }
        $html .= '</tr>';
        
        // Data
        foreach ($data as $row) {
            $html .= '<tr>';
            foreach ($row as $key => $value) {
                if (!is_numeric($key)) {
                    $html .= '<td>' . $value . '</td>';
                }
            }
            $html .= '</tr>';
        }
        
        $html .= '</table>';
        $pdf->writeHTML($html, true, false, true, false, '');
    } else {
        $pdf->Cell(0, 10, 'No data found', 0, 1);
    }
    
    $pdf->Output($filename . '.pdf', 'D');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reports & Analytics</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        .card-stat {
            transition: transform 0.2s;
        }
        .card-stat:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .table th {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <div class="row mb-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Generate Reports</h5>
                    </div>
                    <div class="card-body">
                        <!-- Report Type Tabs -->
                        <ul class="nav nav-tabs mb-4" id="reportTabs">
                            <li class="nav-item">
                                <a class="nav-link <?php echo $report_type == 'attendance' ? 'active' : ''; ?>" 
                                   href="?page=reports&type=attendance">Attendance</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo $report_type == 'leave' ? 'active' : ''; ?>" 
                                   href="?page=reports&type=leave">Leave</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo $report_type == 'salary' ? 'active' : ''; ?>" 
                                   href="?page=reports&type=salary">Salary</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo $report_type == 'performance' ? 'active' : ''; ?>" 
                                   href="?page=reports&type=performance">Performance</a>
                            </li>
                        </ul>

                        <!-- Filter Form -->
                        <form method="GET" action="" class="row g-3">
                            <input type="hidden" name="page" value="reports">
                            <input type="hidden" name="type" value="<?php echo $report_type; ?>">
                            
                            <?php if($report_type == 'attendance'): ?>
                            <div class="col-md-3">
                                <label>Month</label>
                                <input type="month" name="month" class="form-control" value="<?php echo $month; ?>">
                            </div>
                            <?php endif; ?>
                            
                            <?php if($report_type == 'leave'): ?>
                            <div class="col-md-3">
                                <label>Start Date</label>
                                <input type="date" name="start_date" class="form-control" value="<?php echo $start_date; ?>">
                            </div>
                            <div class="col-md-3">
                                <label>End Date</label>
                                <input type="date" name="end_date" class="form-control" value="<?php echo $end_date; ?>">
                            </div>
                            <?php endif; ?>
                            
                            <div class="col-md-3">
                                <label>Department</label>
                                <select name="department" class="form-control">
                                    <option value="all">All Departments</option>
                                    <?php foreach($departments as $dept): ?>
                                    <option value="<?php echo $dept['department']; ?>" 
                                        <?php echo $department == $dept['department'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($dept['department']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <?php if($report_type == 'attendance'): ?>
                            <div class="col-md-3">
                                <label>Employee</label>
                                <select name="employee" class="form-control">
                                    <option value="all">All Employees</option>
                                    <?php foreach($employees as $emp): ?>
                                    <option value="<?php echo $emp['id']; ?>" 
                                        <?php echo $employee_id == $emp['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($emp['full_name']) . ' - ' . $emp['department']; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <?php endif; ?>
                            
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-filter"></i> Generate Report
                                </button>
                                <?php if (count($report_data) > 0): ?>
                                <div class="btn-group" role="group">
                                    <a href="?page=reports&type=<?php echo $report_type; ?>&export=excel&<?php echo http_build_query($_GET); ?>" 
                                       class="btn btn-success">
                                        <i class="bi bi-file-excel"></i> Export to Excel
                                    </a>
                                    <a href="?page=reports&type=<?php echo $report_type; ?>&export=pdf&<?php echo http_build_query($_GET); ?>" 
                                       class="btn btn-danger">
                                        <i class="bi bi-file-pdf"></i> Export to PDF
                                    </a>
                                    <button type="button" class="btn btn-secondary" onclick="printReport()">
                                        <i class="bi bi-printer"></i> Print
                                    </button>
                                </div>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><?php echo $report_title; ?></h5>
                        <span class="badge bg-primary"><?php echo count($report_data); ?> Records</span>
                    </div>
                    <div class="card-body">
                        <!-- Report Data Table -->
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="reportTable">
                                <thead class="table-dark">
                                    <tr>
                                        <?php if(count($report_data) > 0): ?>
                                        <?php 
                                        $first_row = $report_data[0];
                                        foreach($first_row as $key => $value): 
                                            if(!is_numeric($key)): 
                                        ?>
                                        <th><?php echo ucwords(str_replace('_', ' ', $key)); ?></th>
                                        <?php 
                                            endif;
                                        endforeach; 
                                        ?>
                                        <?php else: ?>
                                        <th colspan="10" class="text-center">No data available for selected criteria</th>
                                        <?php endif; ?>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($report_data as $row): ?>
                                    <tr>
                                        <?php foreach($row as $key => $value): 
                                            if(!is_numeric($key)):
                                                if(strpos($key, 'salary') !== false || strpos($key, 'allowance') !== false): ?>
                                        <td>Rs. <?php echo number_format($value, 2); ?></td>
                                                <?php elseif(strpos($key, 'minutes') !== false): ?>
                                        <td><?php echo $value > 0 ? $value . ' min' : '-'; ?></td>
                                                <?php elseif(strpos($key, 'percentage') !== false): ?>
                                        <td><?php echo $value . '%'; ?></td>
                                                <?php else: ?>
                                        <td><?php echo htmlspecialchars($value ?? '-'); ?></td>
                                                <?php endif; ?>
                                        <?php endif; endforeach; ?>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Print Report
    function printReport() {
        const printContent = document.getElementById('reportTable').outerHTML;
        const originalContent = document.body.innerHTML;
        
        document.body.innerHTML = `
            <html>
                <head>
                    <title>Print Report</title>
                    <style>
                        body { font-family: Arial, sans-serif; margin: 20px; }
                        h2 { text-align: center; margin-bottom: 20px; }
                        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                        th { background-color: #f2f2f2; font-weight: bold; }
                        @media print {
                            .no-print { display: none; }
                        }
                    </style>
                </head>
                <body>
                    <h2><?php echo $report_title; ?></h2>
                    <p><strong>Generated on:</strong> ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}</p>
                    ${printContent}
                    <div class="no-print" style="margin-top: 20px; text-align: center;">
                        <button onclick="window.print()" style="padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer;">
                            Print Report
                        </button>
                        <button onclick="location.reload()" style="padding: 10px 20px; background: #6c757d; color: white; border: none; cursor: pointer;">
                            Close
                        </button>
                    </div>
                    <script>
                        window.onload = function() {
                            window.print();
                        }
                    <\/script>
                </body>
            </html>
        `;
    }
    </script>
</body>
</html>