<?php
session_start();
ob_start();

// Include config and verify connection
try {
    include 'config.php';
    if (!isset($conn) || !$conn) {
        throw new Exception("Database connection not established.");
    }
} catch (Exception $e) {
    error_log("Connection error: " . $e->getMessage());
    die("Error: Unable to connect to the database. Please contact the administrator.");
}

// Check if user is logged in and is employee
if (!isset($_SESSION['username']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'employee') {
    header("Location: index.php");
    exit();
}

// Get employee_id from session
$employee_id = $_SESSION['user_id'];

// Validate inputs
$month = isset($_GET['month']) ? min(max((int)$_GET['month'], 1), 12) : date('m');
$year = isset($_GET['year']) ? min(max((int)$_GET['year'], 2000), 2030) : date('Y');

// Fetch approved payroll for the employee
$sql = "SELECT * FROM payroll_records WHERE employee_id = ? AND month = ? AND year = ? AND status = 'approved'";
$stmt = $conn->prepare($sql);
$stmt->bind_param("iii", $employee_id, $month, $year);
$stmt->execute();
$result = $stmt->get_result();
$payroll_data = $result->fetch_assoc();
$stmt->close();

// Fetch payroll history for the employee
$sql_history = "SELECT month, year FROM payroll_records WHERE employee_id = ? AND status = 'approved' GROUP BY year, month ORDER BY year DESC, month DESC";
$stmt_history = $conn->prepare($sql_history);
$stmt_history->bind_param("i", $employee_id);
$stmt_history->execute();
$result_history = $stmt_history->get_result();
$history_months = [];
while ($row = $result_history->fetch_assoc()) {
    $history_months[] = $row;
}
$stmt_history->close();

ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Payroll Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 250px;
            background: #2c3e50;
            color: #fff;
            padding: 15px;
            transition: transform 0.3s ease;
            position: fixed;
            top: 0;
            bottom: 0;
            z-index: 1000;
            transform: translateX(-250px);
        }
        .sidebar.active {
            transform: translateX(0);
        }
        .sidebar h2 {
            font-size: 1rem;
            margin-bottom: 15px;
        }
        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 8px 10px;
            display: block;
            border-radius: 4px;
            margin-bottom: 5px;
            font-size: 0.9rem;
        }
        .sidebar a:hover {
            background: #1abc9c;
        }
        .sidebar a.active {
            background: #1abc9c;
        }
        .sidebar .dropdown-menu {
            background: #34495e;
            border: none;
            padding: 0;
        }
        .sidebar .dropdown-menu a {
            color: #fff;
            padding: 8px 20px;
            font-size: 0.85rem;
        }
        .sidebar .dropdown-menu a:hover {
            background: #1abc9c;
        }
        .sidebar .dropdown-toggle::after {
            float: right;
            margin-top: 8px;
        }
        .hamburger {
            position: fixed;
            top: 10px;
            left: 10px;
            z-index: 1100;
            background: #2c3e50;
            color: #fff;
            border: none;
            padding: 8px;
            border-radius: 4px;
            cursor: pointer;
        }
        .content {
            flex: 1;
            padding: 15px;
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }
        .content.active {
            margin-left: 250px;
        }
        h1 {
            font-size: 1.5rem;
            margin-bottom: 15px;
            color: #333;
        }
        .table-responsive {
            font-size: 0.85rem;
        }
        .table th, .table td {
            padding: 8px;
            border: 1px solid #ddd;
            vertical-align: middle;
        }
        .table th {
            background: #2c3e50;
            color: white;
        }
        .btn {
            padding: 6px 12px;
            font-size: 0.85rem;
            touch-action: manipulation;
        }
        .btn-spacing {
            margin: 5px;
        }
        @media (max-width: 576px) {
            .table-responsive {
                font-size: 0.75rem;
            }
            h1 {
                font-size: 1.2rem;
            }
        }
    </style>
</head>
<body>
    <!-- Hamburger Menu -->
    <button class="hamburger" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <h2>Mypeopleconnect</h2>
        <a class="dropdown-toggle" href="dashboard_employee.php" aria-expanded="false">
            <i class="fas fa-home"></i> Employee Dashboard
        </a>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-home"></i> DAP
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="employee_details.php">Employee Details</a></li>
                <li><a class="dropdown-item" href="policies.php">Policies</a></li>
            </ul>
        </div>
        <div class="dropdown">
            <a class="dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-users"></i> CAB
            </a>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="employee_payroll.php">Payroll</a></li>
                <li><a class="dropdown-item" href="leave.php">Leave</a></li>
                <li><a class="dropdown-item" href="grievance.php">Grievance Portal</a></li>
            </ul>
        </div>
        <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <!-- Main Content -->
    <div class="content" id="content">
        <h1 class="text-primary text-center">Employee Payroll Portal</h1>

        <!-- Selection Form -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h2>Select Month/Year</h2>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <label for="month" class="form-label">Select Month:</label>
                        <select class="form-select" id="month" name="month">
                            <?php for ($i = 1; $i <= 12; $i++): ?>
                                <option value="<?= $i ?>" <?= ($month == $i) ? 'selected' : ''; ?>>
                                    <?= date('F', mktime(0, 0, 0, $i, 10)); ?>
                                </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="year" class="form-label">Select Year:</label>
                        <input type="number" class="form-control" id="year" name="year" value="<?= $year; ?>" min="2000" max="2030">
                    </div>
                    <div class="col-md-4 align-self-end">
                        <button type="submit" class="btn btn-primary">Load Payroll</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Payroll Details -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h2>Payroll Details for <?= date('F', mktime(0, 0, 0, $month, 10)); ?> <?= $year; ?></h2>
            </div>
            <div class="card-body">
                <?php if (!$payroll_data): ?>
                    <div class="alert alert-info">No approved payroll record found for this period.</div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>ECODE</th>
                                    <th>Basic Salary</th>
                                    <th>HRA</th>
                                    <th>Other Allowance</th>
                                    <th>Total Gross Salary</th>
                                    <th>IT</th>
                                    <th>PT</th>
                                    <th>PF</th>
                                    <th>VPF</th>
                                    <th>ESI</th>
                                    <th>Loan Principal</th>
                                    <th>Loan Interest</th>
                                    <th>Salary Advance</th>
                                    <th>Late Hours</th>
                                    <th>Unpaid Leave</th>
                                    <th>Other Deductions</th>
                                    <th>Total Deductions</th>
                                    <th>Net Earnings</th>
                                    <th>Office Working Days</th>
                                    <th>No of Absent</th>
                                    <th>No of Present</th>
                                    <th>Unpaid Leave Difference</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><?= htmlspecialchars($payroll_data['ecode'] ?? 'N/A'); ?></td>
                                    <td><?= number_format($payroll_data['basic_salary'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['hra'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['other_allowance'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['total_gross_salary'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['it'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['pt'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['pf'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['vpf'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['esi'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['loan_principal'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['loan_interest'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['salary_advance'] ?? 0, 2); ?></td>
                                    <td><?= $payroll_data['late_hours'] ?? '0'; ?></td>
                                    <td><?= $payroll_data['unpaid_leave'] ?? '0'; ?></td>
                                    <td><?= number_format($payroll_data['other_deductions'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['total_deductions'] ?? 0, 2); ?></td>
                                    <td><?= number_format($payroll_data['net_earnings'] ?? 0, 2); ?></td>
                                    <td><?= $payroll_data['office_working_days'] ?? '0'; ?></td>
                                    <td><?= $payroll_data['no_of_absent'] ?? '0'; ?></td>
                                    <td><?= $payroll_data['no_of_present'] ?? '0'; ?></td>
                                    <td><?= $payroll_data['unpaid_leave_difference'] ?? '0'; ?></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Payroll History -->
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h2>Payroll History</h2>
            </div>
            <div class="card-body">
                <?php if (empty($history_months)): ?>
                    <div class="alert alert-info">No payroll history available.</div>
                <?php else: ?>
                    <div class="list-group">
                        <?php foreach ($history_months as $hist): ?>
                            <a href="?month=<?= $hist['month']; ?>&year=<?= $hist['year']; ?>" class="list-group-item list-group-item-action">
                                <?= date('F', mktime(0, 0, 0, $hist['month'], 10)); ?> <?= $hist['year']; ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const content = document.getElementById('content');
            sidebar.classList.toggle('active');
            content.classList.toggle('active');
        }
    </script>
</body>
</html>