<?php
session_start();
include 'config.php';
require_once('fpdf/fpdf.php'); // Adjust path if FPDF is in a subdirectory, e.g., 'fpdf/fpdf.php'

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

// Get selected month/year
$selected_month = isset($_GET['month']) ? (int)$_GET['month'] : date('m');
$selected_year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');

// Validate
if ($selected_month < 1 || $selected_month > 12) $selected_month = date('m');
if ($selected_year < 2000 || $selected_year > 2100) $selected_year = date('Y');

$month_name = date('F', mktime(0, 0, 0, $selected_month, 1));

// Sample data from your input (for testing, will be replaced by DB query)
$sample_data = [
    [
        'first_name' => 'GM',
        'last_name' => 'Director',
        'designation' => 'Manager',
        'division' => 'IT',
        'location' => 'Chennai',
        'basic_salary' => 30000.00,
        'hra' => 0.00,
        'other_allowance' => 0.00,
        'total_gross_salary' => 30000.00,
        'it' => 0.00,
        'pt' => 0.00,
        'pf' => 0.00,
        'vpf' => 0.00,
        'esi' => 0.00,
        'loan_principal' => 0.00,
        'loan_interest' => 0.00,
        'salary_advance' => 0.00,
        'late_hours' => 0,
        'unpaid_leave' => 0,
        'other_deductions' => 0.00,
        'total_deductions' => 0.00,
        'net_earnings' => 30000.00,
        'status' => 'approved'
    ],
    [
        'first_name' => 'HR',
        'last_name' => 'MPC Manager',
        'designation' => 'Manager',
        'division' => 'IT',
        'location' => 'Chennai',
        'basic_salary' => 30000.00,
        'hra' => 4000.00,
        'other_allowance' => 2000.00,
        'total_gross_salary' => 36000.00,
        'it' => 100.00,
        'pt' => 0.00,
        'pf' => 0.00,
        'vpf' => 0.00,
        'esi' => 0.00,
        'loan_principal' => 0.00,
        'loan_interest' => 0.00,
        'salary_advance' => 0.00,
        'late_hours' => 0,
        'unpaid_leave' => 0,
        'other_deductions' => 0.00,
        'total_deductions' => 100.00,
        'net_earnings' => 35900.00,
        'status' => 'approved'
    ],
    [
        'first_name' => 'Muthu',
        'last_name' => 'MPC Executive',
        'designation' => 'Executive',
        'division' => 'IT',
        'location' => 'Chennai',
        'basic_salary' => 30000.00,
        'hra' => 4000.00,
        'other_allowance' => 2000.00,
        'total_gross_salary' => 36000.00,
        'it' => 100.00,
        'pt' => 0.00,
        'pf' => 0.00,
        'vpf' => 0.00,
        'esi' => 0.00,
        'loan_principal' => 0.00,
        'loan_interest' => 0.00,
        'salary_advance' => 0.00,
        'late_hours' => 0,
        'unpaid_leave' => 0,
        'other_deductions' => 0.00,
        'total_deductions' => 100.00,
        'net_earnings' => 35900.00,
        'status' => 'approved'
    ]
];

// Fetch payroll data from database
$query = "SELECT u.first_name, u.last_name, u.designation, u.division, u.location,
                 p.basic_salary, p.hra, p.other_allowance, p.total_gross_salary,
                 p.it, p.pt, p.pf, p.vpf, p.esi, p.loan_principal, p.loan_interest,
                 p.salary_advance, p.late_hours, p.unpaid_leave, p.other_deductions,
                 p.total_deductions, p.net_earnings, p.status
          FROM users u
          INNER JOIN payroll_records p ON u.id = p.employee_id
          WHERE p.month = ? AND p.year = ? AND p.status IN ('approved', 'sent')
          AND u.status = 'active' AND u.role != 'superadmin'
          ORDER BY u.division, u.first_name";

$stmt = mysqli_prepare($conn, $query);
if ($stmt === false) {
    die("Prepare failed: " . mysqli_error($conn));
}
mysqli_stmt_bind_param($stmt, "ii", $selected_month, $selected_year);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

// Use database data if available, else fallback to sample data
$payroll_data = [];
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $payroll_data[] = $row;
    }
} else {
    $payroll_data = $sample_data; // Fallback to sample data for testing
}

if (empty($payroll_data)) {
    die("No approved payroll data found for " . $month_name . " " . $selected_year . ". Please approve payroll first.");
}

// Initialize totals
$total_gross = 0;
$total_deductions = 0;
$total_net = 0;
foreach ($payroll_data as $row) {
    $total_gross += $row['total_gross_salary'];
    $total_deductions += $row['total_deductions'];
    $total_net += $row['net_earnings'];
}
mysqli_stmt_close($stmt);

// Create PDF in landscape orientation with A3 size
class PDF extends FPDF {
    function Header() {
        $this->SetFont('Arial', 'B', 16);
        $this->SetTextColor(44, 62, 80); // #2c3e50
        $this->Cell(0, 12, 'Payroll Report', 0, 1, 'C');
        $this->SetFont('Arial', '', 12);
        $this->Cell(0, 8, 'Month: ' . date('F', mktime(0, 0, 0, $_GET['month'], 1)), 0, 1, 'L');
        $this->Cell(0, 8, 'Year: ' . $_GET['year'], 0, 1, 'L');
        $this->Cell(0, 8, 'Generated By: ' . $_SESSION['username'], 0, 1, 'L');
        $this->Cell(0, 8, 'Generated On: ' . date('Y-m-d H:i:s'), 0, 1, 'L');
        $this->Ln(5);
    }

    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 10);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
    }

    function PayrollTable($header, $data) {
        // Colors
        $header_fill = array(44, 62, 80); // #2c3e50
        $totals_fill = array(26, 188, 156); // #1abc9c
        $this->SetFont('Arial', 'B', 8);
        $this->SetFillColor($header_fill[0], $header_fill[1], $header_fill[2]);
        $this->SetTextColor(255);
        $this->SetDrawColor(0);

        // Column widths (adjusted to fit A3 landscape, total ~380mm for 22 columns)
        $w = array(30, 20, 20, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15); // Average ~17mm per column, total ~374mm

        // Header
        for ($i = 0; $i < count($header); $i++) {
            $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1);
        }
        $this->Ln();

        // Data
        $this->SetFont('Arial', '', 7);
        $this->SetTextColor(0);
        foreach ($data as $row) {
            $this->Cell($w[0], 6, $row['first_name'] . ' ' . $row['last_name'], 1);
            $this->Cell($w[1], 6, $row['designation'], 1);
            $this->Cell($w[2], 6, $row['division'], 1);
            $this->Cell($w[3], 6, ucfirst($row['location']), 1);
            $this->Cell($w[4], 6, number_format($row['basic_salary'], 2), 1);
            $this->Cell($w[5], 6, number_format($row['hra'], 2), 1);
            $this->Cell($w[6], 6, number_format($row['other_allowance'], 2), 1);
            $this->Cell($w[7], 6, number_format($row['total_gross_salary'], 2), 1);
            $this->Cell($w[8], 6, number_format($row['it'], 2), 1);
            $this->Cell($w[9], 6, number_format($row['pt'], 2), 1);
            $this->Cell($w[10], 6, number_format($row['pf'], 2), 1);
            $this->Cell($w[11], 6, number_format($row['vpf'], 2), 1);
            $this->Cell($w[12], 6, number_format($row['esi'], 2), 1);
            $this->Cell($w[13], 6, number_format($row['loan_principal'], 2), 1);
            $this->Cell($w[14], 6, number_format($row['loan_interest'], 2), 1);
            $this->Cell($w[15], 6, number_format($row['salary_advance'], 2), 1);
            $this->Cell($w[16], 6, $row['late_hours'], 1);
            $this->Cell($w[17], 6, $row['unpaid_leave'], 1);
            $this->Cell($w[18], 6, number_format($row['other_deductions'], 2), 1);
            $this->Cell($w[19], 6, number_format($row['total_deductions'], 2), 1);
            $this->Cell($w[20], 6, number_format($row['net_earnings'], 2), 1);
            $this->Cell($w[21], 6, $row['status'], 1);
            $this->Ln();
        }

        // Totals
        global $total_gross, $total_deductions, $total_net;
        $this->SetFont('Arial', 'B', 8);
        $this->SetFillColor($totals_fill[0], $totals_fill[1], $totals_fill[2]);
        $this->SetTextColor(255);
        $this->Cell($w[0] + $w[1] + $w[2] + $w[3], 6, 'TOTALS', 1, 0, 'R', 1);
        $this->Cell($w[4], 6, '', 1, 0, '', 1);
        $this->Cell($w[5], 6, '', 1, 0, '', 1);
        $this->Cell($w[6], 6, '', 1, 0, '', 1);
        $this->Cell($w[7], 6, number_format($total_gross, 2), 1, 0, 'C', 1);
        $this->Cell($w[8], 6, '', 1, 0, '', 1);
        $this->Cell($w[9], 6, '', 1, 0, '', 1);
        $this->Cell($w[10], 6, '', 1, 0, '', 1);
        $this->Cell($w[11], 6, '', 1, 0, '', 1);
        $this->Cell($w[12], 6, '', 1, 0, '', 1);
        $this->Cell($w[13], 6, '', 1, 0, '', 1);
        $this->Cell($w[14], 6, '', 1, 0, '', 1);
        $this->Cell($w[15], 6, '', 1, 0, '', 1);
        $this->Cell($w[16], 6, '', 1, 0, '', 1);
        $this->Cell($w[17], 6, '', 1, 0, '', 1);
        $this->Cell($w[18], 6, '', 1, 0, '', 1);
        $this->Cell($w[19], 6, number_format($total_deductions, 2), 1, 0, 'C', 1);
        $this->Cell($w[20], 6, number_format($total_net, 2), 1, 0, 'C', 1);
        $this->Cell($w[21], 6, '', 1, 0, '', 1);
        $this->Ln();
    }
}

$pdf = new PDF('L', 'mm', 'A3'); // A3 landscape orientation
$pdf->AliasNbPages();
$pdf->AddPage();

// Define headers
$header = array('Employee Name', 'Designation', 'division', 'Location', 'Basic Salary', 'HRA', 'Other Allowance',
                'Total Gross', 'IT', 'PT', 'PF', 'VPF', 'ESI', 'Loan Principal', 'Loan Interest',
                'Salary Advance', 'Late Hours', 'Unpaid Leave', 'Other Deductions', 'Total Deductions', 'Net Earnings', 'Status');

// Generate table
$pdf->PayrollTable($header, $payroll_data);

// Output PDF
$filename = 'Payroll_Report_' . $month_name . '_' . $selected_year . '.pdf';
$pdf->Output($filename, 'D'); // 'D' for download

mysqli_close($conn);
?>

