<?php
date_default_timezone_set('Asia/Kolkata');

session_start();
require 'config.php';

if (!isset($_SESSION['username']) || !in_array($_SESSION['role'], ['admin','superadmin','manager'])) {
    header("Location: index.php");
    exit;
}

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("<div class='alert alert-danger text-center my-5'>Invalid payslip request</div>");
}

$id = (int)$_GET['id'];

$conn->set_charset('utf8mb4');

$stmt = $conn->prepare("
    SELECT 
        p.*,
        u.username          AS emp_username,
        u.first_name,
        u.last_name,
        u.division,
        u.basic_salary,
        u.id                AS emp_id
    FROM payroll p
    JOIN users u ON u.id = p.emp_id
    WHERE p.id = ?
");
$stmt->bind_param("i", $id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$row) {
    die("<div class='alert alert-warning text-center my-5'>Payslip record not found</div>");
}

$month_raw = $row['month'] ?? date('Y-m');
$month_obj = DateTime::createFromFormat('Y-m', $month_raw);
$month_name = $month_obj ? $month_obj->format('F Y') : $month_raw;

$full_name = trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
if (empty($full_name)) $full_name = $row['emp_username'] ?? '—';

function disp($v, $dec = 2) {
    return number_format((float)$v, $dec, '.', ',');
}

$salary_used   = $row['salary'] > 0 ? $row['salary'] : ($row['basic_salary'] ?? 0);
$working_days  = (int)($row['working_days'] ?? 30);
$paid_days     = (int)($row['paid_days'] ?? 0);
$wages         = $working_days > 0 ? ($salary_used / $working_days) * $paid_days : 0;

$basic         = $wages * 0.40;
$da            = $wages * 0.20;
$hra           = $wages * 0.20;
$medical       = $wages * 0.10;
$conveyance    = $wages * 0.10;
$gross         = $basic + $da + $hra + $medical + $conveyance;

$epf_eligible  = !empty($row['epf_eligible']);
$epf_calc      = $epf_eligible ? min(($basic + $da + $hra) * 0.12, 1800) : 0;
$epf_final     = $row['epf_manual_amt'] > 0 ? $row['epf_manual_amt'] : $epf_calc;

$esi_eligible  = !empty($row['esi_eligible']);
$esi           = ($esi_eligible && $gross <= 21000) ? $gross * 0.0075 : 0;

$net_pay = $gross 
         + ($row['travel_allow']   ?? 0)
         + ($row['two_wheeler_maint'] ?? 0)
         + ($row['outstanding_amt'] ?? 0)
         - $epf_final
         - $esi
         - ($row['tds'] ?? 0)
         - ($row['advance'] ?? 0)
         + ($row['round_off'] ?? 0);

$company_name    = "Arostar Enterprises Pvt Ltd";
$company_addr    = "No:23,24,25 Arul Murugan Nagar, Pazhanthandalam Village, Thirumudivakkam, Chennai, Tamil Nadu - 600132";
$company_pan     = "PAN: AALCA0811F";
$company_gst     = "GSTIN: 33AALCA0811F1Z9";
$company_email   = "accounts@arostarint.com";
$company_phone   = "044 4557 4630";
$company_logo    = 'assets/arostar-logo.jpg';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payslip - <?= htmlspecialchars($full_name) ?> - <?= htmlspecialchars($month_name) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <style>
        :root {
            --primary: #004aad;
            --border: #d1d5db;
            --text: #1f2937;
        }
        body {
            background: #f9fafb;
            font-family: 'Segoe UI', Arial, sans-serif;
            color: var(--text);
            margin: 0;
            padding: 10px;
            font-size: 13px;
            line-height: 1.35;
        }
        .payslip-container {
            max-width: 920px;
            margin: 0 auto;
            background: white;
            border-radius: 6px;
            box-shadow: 0 3px 12px rgba(0,0,0,0.07);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #004aad, #002855);
            color: white;
            padding: 14px 20px;
        }
        .header-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
        }
        .logo img {
            max-height: 55px;
            background: white;
            border-radius: 4px;
            padding: 4px;
        }
        .company-name {
            font-size: 1.55rem;
            font-weight: 700;
        }
        .company-meta {
            font-size: 0.81rem;
            opacity: 0.95;
        }
        .title {
            text-align: center;
            font-size: 1.28rem;
            font-weight: 600;
            margin: 10px 0 4px;
        }
        .content {
            padding: 14px 20px 10px;
        }
        .section-title {
            font-size: 1.05rem;
            font-weight: 600;
            color: var(--primary);
            margin: 12px 0 5px;
            border-bottom: 1px solid var(--primary);
            padding-bottom: 3px;
        }
        .salary-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 11.8px;
        }
        .salary-table td, .salary-table th {
            padding: 4.5px 6px;
            border: 1px solid var(--border);
        }
        .salary-table th {
            background: #f3f4f6;
            font-weight: 600;
        }
        .amount {
            text-align: right;
            width: 110px;
        }
        .gross { background: #e0f2fe; font-weight: 600; }
        .net   { background: #ecfdf5; font-weight: bold; font-size: 13px; }
        .deduct { color: #b91c1c; }
        .left-col { background: #f8f9fa; }
        .right-col { background: #fff5f5; }
        .footer-notice {
            text-align: center;
            color: #4b5563;
            font-size: 0.84rem;
            font-style: italic;
            margin: 10px 0;
            padding-top: 6px;
            border-top: 1px solid #e5e7eb;
        }
        .actions {
            text-align: center;
            margin: 14px 0;
        }
        @media print {
            @page { size: A4 portrait; margin: 7mm 9mm 5mm 9mm; }
            body { margin: 0; padding: 0; font-size: 9.8pt; background: white; }
            .payslip-container { box-shadow: none; border-radius: 0; }
            .header { padding: 10px 16px !important; }
            .logo img { max-height: 42px !important; }
            .content { padding: 10px 16px 6px !important; }
            .salary-table td, .salary-table th { padding: 3.5px 5px !important; font-size: 9.4pt !important; }
            .actions, .no-print { display: none !important; }
            .print-only { display: block !important; font-size: 8.8pt; color: #555; margin-top: 6px; }
        }
    </style>
</head>
<body>

<div class="payslip-container" id="payslip">

    <div class="header">
        <div class="header-top">
            <div class="logo">
                <?php if(file_exists($company_logo)): ?>
                    <img src="<?= htmlspecialchars($company_logo) ?>" alt="Logo">
                <?php else: ?>
                    <span class="bg-white text-dark px-2 py-1 fw-bold rounded">LOGO</span>
                <?php endif; ?>
            </div>
            <div class="text-end">
                <div class="company-name"><?= htmlspecialchars($company_name) ?></div>
                <div class="company-meta">
                    <?= $company_addr ?><br>
                    <?= htmlspecialchars($company_pan) ?> • <?= htmlspecialchars($company_gst) ?><br>
                    <?= htmlspecialchars($company_email) ?> • <?= htmlspecialchars($company_phone) ?>
                </div>
            </div>
        </div>
        <div class="title">Salary Payslip – <?= htmlspecialchars($month_name) ?></div>
    </div>

    <div class="content">

        <div class="row g-3 mb-3">
            <div class="col-6">
                <div class="section-title">Employee Details</div>
                <table class="table table-borderless table-sm">
                    <tr><td width="110">Name</td><td><strong><?= htmlspecialchars($full_name) ?></strong></td></tr>
                    <tr><td>Emp ID</td><td><?= htmlspecialchars($row['emp_id']) ?></td></tr>
                    <tr><td>Division</td><td><?= htmlspecialchars($row['division'] ?: '—') ?></td></tr>
                    <tr><td>Bank Name</td><td>—</td></tr>
                    <tr><td>A/c Number</td><td>—</td></tr>
                    <tr><td>IFSC Code</td><td>—</td></tr>
                </table>
            </div>
            <div class="col-6">
                <div class="section-title">Pay Period</div>
                <table class="table table-borderless table-sm">
                    <tr><td width="110">Month</td><td><?= htmlspecialchars($month_name) ?></td></tr>
                    <tr><td>Working Days</td><td><?= $working_days ?></td></tr>
                    <tr><td>Paid Days</td><td><?= $paid_days ?></td></tr>
                    <tr><td>Absent</td><td><?= $row['absent_days'] ?? 0 ?></td></tr>
                </table>
            </div>
        </div>

        <div class="section-title">Earnings & Deductions</div>
        <div class="row g-0">
            <!-- Left Column: Earnings + Additions -->
            <div class="col-6 left-col">
                <table class="salary-table">
                    <thead>
                        <tr><th>Earnings</th><th class="amount">Amount (₹)</th></tr>
                    </thead>
                    <tbody>
                        <tr><td>Basic Salary</td><td class="amount"><?= disp($basic) ?></td></tr>
                        <tr><td>Dearness Allowance</td><td class="amount"><?= disp($da) ?></td></tr>
                        <tr><td>HRA</td><td class="amount"><?= disp($hra) ?></td></tr>
                        <tr><td>Medical Allowance</td><td class="amount"><?= disp($medical) ?></td></tr>
                        <tr><td>Conveyance Allowance</td><td class="amount"><?= disp($conveyance) ?></td></tr>
                        <tr class="gross"><td><strong>Gross Earnings</strong></td><td class="amount"><?= disp($gross) ?></td></tr>
                    </tbody>
                </table>

                <div class="p-2 bg-light fw-bold">Additions</div>
                <table class="salary-table">
                    <tbody>
                        <tr><td>Travel Allowance</td><td class="amount"><?= disp($row['travel_allow'] ?? 0) ?></td></tr>
                        <tr><td>2 Wheeler Maintenance</td><td class="amount"><?= disp($row['two_wheeler_maint'] ?? 0) ?></td></tr>
                        <tr><td>Outstanding Amount</td><td class="amount"><?= disp($row['outstanding_amt'] ?? 0) ?></td></tr>
                    </tbody>
                </table>
            </div>

            <!-- Right Column: Deductions -->
            <div class="col-6 right-col">
                <table class="salary-table">
                    <thead>
                        <tr><th>Deductions</th><th class="amount">Amount (₹)</th></tr>
                    </thead>
                    <tbody>
                        <tr><td>EPF Contribution</td><td class="amount deduct"><?= disp($epf_final) ?></td></tr>
                        <tr><td>ESI Contribution</td><td class="amount deduct"><?= disp($esi) ?></td></tr>
                        <tr><td>TDS</td><td class="amount deduct"><?= disp($row['tds'] ?? 0) ?></td></tr>
                        <tr><td>Advance Recovery</td><td class="amount deduct"><?= disp($row['advance'] ?? 0) ?></td></tr>
                        <tr class="net">
                            <td><strong>NET PAY</strong></td>
                            <td class="amount text-success"><?= disp($net_pay) ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="text-center text-muted small mt-2 no-print">
            Generated: <?= date('d M Y h:i A') ?> • Status: 
            <?php
            $status = $row['status'] ?? 'draft';
            echo match($status) {
                'approved' => '<span class="badge bg-success">Approved</span>',
                'pending'  => '<span class="badge bg-warning text-dark">Pending</span>',
                default    => '<span class="badge bg-info">Draft</span>'
            };
            ?>
        </div>

        <div class="footer-notice no-print">
            This is a computer-generated payslip – no signature required
        </div>

        <div class="actions no-print text-center">
            <button onclick="window.print()" class="btn btn-primary me-2">
                <i class="fas fa-print"></i> Print
            </button>
            <button onclick="exportToPDF()" class="btn btn-success me-2">
                <i class="fas fa-file-pdf"></i> PDF
            </button>
            <a href="payroll.php?month=<?= urlencode($row['month'] ?? date('Y-m')) ?>" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left"></i> Back
            </a>
        </div>

        <div class="footer-notice print-only text-center">
            Computer generated payslip – no signature required
        </div>

    </div>
</div>

<script>
async function exportToPDF() {
    const { jsPDF } = window.jspdf;
    const element = document.getElementById('payslip');
    const btn = document.querySelector('button[onclick="exportToPDF()"]');
    
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Generating...';
    btn.disabled = true;

    try {
        const canvas = await html2canvas(element, {
            scale: 2.3,
            useCORS: true,
            logging: false,
            backgroundColor: '#ffffff'
        });

        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });

        const pdfW = pdf.internal.pageSize.getWidth();
        const pdfH = pdf.internal.pageSize.getHeight();
        const ratio = Math.min(pdfW / canvas.width, (pdfH - 6) / canvas.height);
        const x = (pdfW - canvas.width * ratio) / 2;

        pdf.addImage(imgData, 'PNG', x, 3, canvas.width * ratio, canvas.height * ratio);
        pdf.save(`Payslip_${'<?= addslashes(htmlspecialchars($full_name)) ?>'.replace(/\s+/g,'_')}_${'<?= addslashes(htmlspecialchars($month_name)) ?>'.replace(/\s+/g,'_')}.pdf`);
    } catch (err) {
        alert('PDF generation failed. Use Print → Save as PDF.');
        console.error(err);
    }

    btn.innerHTML = '<i class="fas fa-file-pdf"></i> PDF';
    btn.disabled = false;
}
</script>

</body>
</html>