<?php
session_start();
include 'config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php"); exit;
}

$emp_id = $_GET['emp_id'] ?? $_SESSION['user_id'];
$month = $_GET['month'] ?? ''; // '2025-04'

if ($_SESSION['role'] !== 'admin' && $emp_id != $_SESSION['user_id']) {
    die("Access denied.");
}

if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
    die("Invalid month.");
}

$stmt = $conn->prepare("SELECT p.*, u.name, u.bank_ac, u.ifsc FROM payroll p 
                        LEFT JOIN users u ON p.emp_id = u.id 
                        WHERE p.emp_id = ? AND p.month = ?");
$stmt->bind_param("is", $emp_id, $month);
$stmt->execute();
$p = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$p) die("Payslip not found.");

$name = $p['name'] ?? 'Employee';
$monthName = date('F Y', strtotime($p['month'] . '-01'));
?>

<!DOCTYPE html>
<html>
<head>
    <title>Payslip - <?= $name ?> - <?= $monthName ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @page { size: A4; margin: 10mm; }
        body { font-family: Arial; padding: 20px; background: #f8f9fa; }
        .payslip { max-width: 210mm; margin: 0 auto; background: white; padding: 20mm; border: 1px solid #ddd; }
        table { font-size: 13px; }
        @media print { body { background: white; } .no-print { display: none; } }
    </style>
</head>
<body>
<div class="payslip shadow">
    <h2 class="text-center">Arostar Enterprises Pvt Ltd</h2>
    <h4 class="text-center">Payslip for <?= $monthName ?></h4>
    <hr>
    <p><strong>Employee:</strong> <?= htmlspecialchars($name) ?> | <strong>Month:</strong> <?= $monthName ?></p>

    <table class="table table-bordered">
        <tr><th>Earnings</th><th>Amount</th><th>Deductions</th><th>Amount</th></tr>
        <tr>
            <td>Basic + DA</td><td>₹<?= number_format($p['basic'] + $p['da'], 2) ?></td>
            <td>EPF</td><td>₹<?= number_format($p['epf'], 2) ?></td>
        </tr>
        <tr>
            <td>HRA</td><td>₹<?= number_format($p['hra'], 2) ?></td>
            <td>ESI</td><td>₹<?= number_format($p['esi'], 2) ?></td>
        </tr>
        <tr>
            <td>Allowances</td><td>₹<?= number_format($p['medical_allow'] + $p['conveyance_allow'], 2) ?></td>
            <td>TDS + Advance</td><td>₹<?= number_format($p['tds'] + $p['advance'], 2) ?></td>
        </tr>
        <tr class="table-success">
            <td><strong>Net Pay</strong></td>
            <td><strong>₹<?= number_format($p['grand_total'], 2) ?></strong></td>
            <td colspan="2"><strong>This is a computer-generated payslip</strong></td>
        </tr>
    </table>
</div>

<div class="text-center mt-4 no-print">
    <button onclick="window.print()" class="btn btn-primary">Print</button>
    <a href="dashboard_employee.php" class="btn btn-secondary">Back</a>
</div>
</body>
</html>