<?php
// payslip.php - portrait A4 single-page payslip, logo from assets/arostar-logo.jpg
// Updated: outstanding_amt treated as AMOUNT OWED TO EMPLOYEE (ADDED to payable),
// table updated to show outstanding on earnings/adjustments side and excluded from deductions.
session_start();
include 'config.php';

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

$role = $_SESSION['role'] ?? '';
$is_admin = in_array($role, ['admin','superadmin']);

// show nice HTML instead of raw die()
function payslip_error($msg) {
    $safe = htmlspecialchars($msg);
    echo "<!doctype html><html><head><meta charset='utf-8'>
        <title>Payslip - Error</title>
        <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css' rel='stylesheet'>
        </head><body class='bg-light'>
        <div class='container py-5'>
            <div class='card shadow-sm'>
                <div class='card-body'>
                    <h4 class='text-danger mb-3'>Payslip Error</h4>
                    <p>{$safe}</p>
                    <a href='payroll.php' class='btn btn-primary btn-sm'>Back to Payroll</a>
                    <a href='attendance.php' class='btn btn-secondary btn-sm ms-2'>Attendance</a>
                </div>
            </div>
        </div>
        </body></html>";
    exit;
}

// ensure charset
if (method_exists($conn, 'set_charset')) {
    $conn->set_charset('utf8mb4');
}

// Logo path (relative)
$company_logo = 'assets/arostar-logo.jpg';
$company_logo_url = ''; // not used; left as placeholder

// Detect user table columns (common variants)
$user_emp_code_col = null;
$user_name_col = null;
$user_basic_col = null;
$user_div_col = null;
$user_bank_col = null;
$user_ifsc_col = null;
$user_uan_col = null;
$user_pf_col = null;
$user_esi_col = null;
$user_paymode_col = null;

$dbname = '';
$db_res = $conn->query("SELECT DATABASE() AS dbname");
if ($db_res) {
    $row_db = $db_res->fetch_assoc();
    $dbname = $row_db['dbname'] ?? '';
}

if ($dbname) {
    $wanted = [
        'emp_code','empid','emp_id',
        'name','full_name',
        'basic_salary','basic',
        'division','dept',
        'bank_account','bank_ac','account_no','account_number','bank_account_no',
        'ifsc','ifsc_code','ifsc_no','ifsccode',
        'uan','uan_number',
        'pf','pf_no','pf_number','pfnumber',
        'esi','esi_no','esi_number',
        'payment_mode','pay_mode','paymethod','pay_method','payment_method'
    ];
    $in = "'" . implode("','", array_map('addslashes', $wanted)) . "'";
    $sqlCols = "
        SELECT COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users'
          AND COLUMN_NAME IN ($in)
    ";
    $col_stmt = $conn->prepare($sqlCols);
    if ($col_stmt) {
        $col_stmt->bind_param("s", $dbname);
        $col_stmt->execute();
        $cr = $col_stmt->get_result();
        $existing = [];
        while ($c = $cr->fetch_assoc()) {
            $existing[strtolower($c['COLUMN_NAME'])] = $c['COLUMN_NAME'];
        }
        $col_stmt->close();

        $user_emp_code_col = $existing['emp_code'] ?? $existing['empid'] ?? $existing['emp_id'] ?? null;
        $user_name_col     = $existing['name'] ?? $existing['full_name'] ?? null;
        $user_basic_col    = $existing['basic_salary'] ?? $existing['basic'] ?? null;
        $user_div_col      = $existing['division'] ?? $existing['dept'] ?? null;

        $user_bank_col     = $existing['bank_account'] ?? $existing['bank_ac'] ?? $existing['account_no'] ?? $existing['account_number'] ?? $existing['bank_account_no'] ?? null;
        $user_ifsc_col     = $existing['ifsc'] ?? $existing['ifsc_code'] ?? $existing['ifsc_no'] ?? $existing['ifsccode'] ?? null;

        $user_uan_col      = $existing['uan'] ?? $existing['uan_number'] ?? null;

        $user_pf_col       = $existing['pf'] ?? $existing['pf_no'] ?? $existing['pf_number'] ?? $existing['pfnumber'] ?? null;
        $user_esi_col      = $existing['esi'] ?? $existing['esi_no'] ?? $existing['esi_number'] ?? null;

        $user_paymode_col  = $existing['payment_mode'] ?? $existing['pay_mode'] ?? $existing['paymethod'] ?? $existing['pay_method'] ?? $existing['payment_method'] ?? null;
    }
}

// ---------- READ INPUT PARAMS (id / emp_id / month) ----------
$raw_id     = $_GET['id']     ?? $_POST['id']     ?? '';
$raw_emp_id = $_GET['emp_id'] ?? $_POST['emp_id'] ?? '';
$month      = $_GET['month']  ?? $_POST['month']  ?? null;

$payroll_id = null;
if ($raw_id !== '' && ctype_digit((string)$raw_id) && (int)$raw_id > 0) {
    $payroll_id = (int)$raw_id;
}

// Build SELECT with detected user columns (we'll reuse it in both lookup modes)
$select_cols = "p.*";
$select_cols .= $user_emp_code_col ? ", u.`{$user_emp_code_col}` AS user_emp_code" : ", p.emp_id AS user_emp_code";
$select_cols .= $user_name_col ? ", u.`{$user_name_col}` AS user_name" : ", COALESCE(p.name, CAST(p.emp_id AS CHAR)) AS user_name";
$select_cols .= $user_basic_col ? ", u.`{$user_basic_col}` AS user_basic_salary" : ", p.basic AS user_basic_salary";
$select_cols .= $user_div_col ? ", u.`{$user_div_col}` AS user_division" : ", p.division AS user_division";
$select_cols .= $user_bank_col    ? ", u.`{$user_bank_col}` AS user_bank"   : ", NULL AS user_bank";
$select_cols .= $user_ifsc_col    ? ", u.`{$user_ifsc_col}` AS user_ifsc"   : ", NULL AS user_ifsc";
$select_cols .= $user_uan_col     ? ", u.`{$user_uan_col}` AS user_uan"     : ", NULL AS user_uan";
$select_cols .= $user_pf_col      ? ", u.`{$user_pf_col}` AS user_pf"       : ", NULL AS user_pf";
$select_cols .= $user_esi_col     ? ", u.`{$user_esi_col}` AS user_esi"     : ", NULL AS user_esi";
$select_cols .= $user_paymode_col ? ", u.`{$user_paymode_col}` AS user_pay_mode" : ", NULL AS user_pay_mode";

$row = null;

// ---------- 1) PRIMARY LOOKUP BY PAYROLL ID ----------
if ($payroll_id !== null) {
    $sql = "SELECT {$select_cols} FROM payroll p LEFT JOIN users u ON p.emp_id = u.id WHERE p.id = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        payslip_error("Database error (prepare by id): " . $conn->error);
    }
    $stmt->bind_param("i", $payroll_id);
    if (!$stmt->execute()) {
        $err = $stmt->error;
        $stmt->close();
        payslip_error("Database error (execute by id): " . $err);
    }
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $stmt->close();
}

// ---------- 2) FALLBACK: LOOKUP BY emp_id + month (OR session user + month) ----------
if (!$row) {
    // determine emp_id to use
    $emp_id = null;
    if ($raw_emp_id !== '' && ctype_digit((string)$raw_emp_id)) {
        $emp_id = (int)$raw_emp_id;
    } elseif (!$is_admin && isset($_SESSION['user_id']) && ctype_digit((string)$_SESSION['user_id'])) {
        // for non-admins, allow their own payslip via month
        $emp_id = (int)$_SESSION['user_id'];
    }

    if ($emp_id !== null && $emp_id > 0 && $month && preg_match('/^\d{4}-\d{2}$/', $month)) {
        $sql_emp = "SELECT {$select_cols} FROM payroll p LEFT JOIN users u ON p.emp_id = u.id WHERE p.emp_id = ? AND p.month = ? LIMIT 1";
        $stmt2 = $conn->prepare($sql_emp);
        if ($stmt2 === false) {
            payslip_error("Database error (prepare by emp/month): " . $conn->error);
        }
        $stmt2->bind_param("is", $emp_id, $month);
        if (!$stmt2->execute()) {
            $err = $stmt2->error;
            $stmt2->close();
            payslip_error("Database error (execute by emp/month): " . $err);
        }
        $res2 = $stmt2->get_result();
        $row = $res2->fetch_assoc();
        $stmt2->close();

        // if row has id, adopt it for later use (recreate, hidden field, etc.)
        if ($row && isset($row['id']) && ctype_digit((string)$row['id'])) {
            $payroll_id = (int)$row['id'];
        }
    }
}

// no record at all
if (!$row) {
    payslip_error("Payslip record not found. Please open from Payroll screen or ensure the employee and month are correct.");
}

// if month provided ensure it matches the row (use row month if mismatch/empty)
if ($month && (!isset($row['month']) || $row['month'] !== $month)) {
    $month = $row['month'];
} elseif (!$month && isset($row['month'])) {
    $month = $row['month'];
}

// final id to use everywhere else
$id = (int)($payroll_id ?? ($row['id'] ?? 0));

// Prefer user's basic_salary from users table ONLY if payroll basic is empty/zero
$payroll_basic_current = isset($row['basic']) ? (float)$row['basic'] : 0;
if ($payroll_basic_current <= 0 &&
    isset($row['user_basic_salary']) &&
    $row['user_basic_salary'] !== null &&
    $row['user_basic_salary'] !== '') {

    $ub = (float)$row['user_basic_salary'];
    if ($ub > 0) {
        $row['basic'] = $ub;
        if (empty($row['salary']) || (float)$row['salary'] == 0.0) {
            $row['salary'] = $ub;
        }
    }
}

// compute derived values
$salary            = (float)($row['salary'] ?? 0);
$working_days      = (float)($row['working_days'] ?? 0);
$absent_days       = (float)($row['absent_days'] ?? 0);
$paid_days         = (float)($row['paid_days'] ?? 0);
$basic             = (float)($row['basic'] ?? 0);
$da                = (float)($row['da'] ?? 0);
$hra               = (float)($row['hra'] ?? 0);
$medical_allow     = (float)($row['medical_allow'] ?? 0);
$conveyance_allow  = (float)($row['conveyance_allow'] ?? 0);
$epf               = (float)($row['epf'] ?? 0);
$esi               = (float)($row['esi'] ?? 0);
$travel_allow      = (float)($row['travel_allow'] ?? 0);
$two_wheeler_maint = (float)($row['two_wheeler_maint'] ?? 0);
$tds               = (float)($row['tds'] ?? 0);
$advance           = (float)($row['advance'] ?? 0);
$outstanding_amt   = (float)($row['outstanding_amt'] ?? 0); // NEW - treated as owed to employee

if ($working_days <= 0) {
    $working_days = $paid_days + $absent_days;
    if ($working_days <= 0) $working_days = 30;
}

$per_day_salary = $working_days > 0 ? round($salary / $working_days, 2) : 0;
$total_wages    = round($per_day_salary * $paid_days, 2);
if ($basic <= 0) $basic = $total_wages;
$gross_salary = $basic + $da + $hra + $medical_allow + $conveyance_allow;
$total        = $gross_salary + $travel_allow + $two_wheeler_maint;

// IMPORTANT: outstanding_amt is an amount owed to the employee carried forward from previous months.
// Treat it as an ADDITION to the payable (i.e., added to earnings/adjustments).
$pending_amt  = $total + $outstanding_amt - $epf - $esi - $tds - $advance;
$grand_total  = $pending_amt;

// POST: recreate single payslip (admin only) - recompute and save some computed fields
$update_message = "";
if ($is_admin && isset($_POST['recreate_payslip']) && $id > 0) {
    $sel_sql = "SELECT p.salary, p.working_days, p.absent_days, p.paid_days, p.basic, p.da, p.hra, p.medical_allow, p.conveyance_allow, p.epf, p.esi, p.travel_allow, p.two_wheeler_maint, p.tds, p.advance, p.outstanding_amt, " .  // added outstanding_amt
               ($user_basic_col ? "u.`{$user_basic_col}` AS user_basic_salary, " : "NULL AS user_basic_salary, ") .
               ($user_bank_col ? "u.`{$user_bank_col}` AS user_bank, " : "NULL AS user_bank, ") .
               ($user_ifsc_col ? "u.`{$user_ifsc_col}` AS user_ifsc, " : "NULL AS user_ifsc, ") .
               "p.emp_id, p.payment_mode FROM payroll p LEFT JOIN users u ON p.emp_id = u.id WHERE p.id = ?";
    $sel2 = $conn->prepare($sel_sql);
    if ($sel2) {
        $sel2->bind_param("i",$id);
        $sel2->execute();
        $r2 = $sel2->get_result()->fetch_assoc();
        $sel2->close();

        $salary            = (float)($r2['salary'] ?? 0);
        $working_days      = (float)($r2['working_days'] ?? 0);
        $absent_days       = (float)($r2['absent_days'] ?? 0);
        $paid_days         = (float)($r2['paid_days'] ?? 0);
        $basic             = (float)($r2['basic'] ?? 0);
        $da                = (float)($r2['da'] ?? 0);
        $hra               = (float)($r2['hra'] ?? 0);
        $medical_allow     = (float)($r2['medical_allow'] ?? 0);
        $conveyance_allow  = (float)($r2['conveyance_allow'] ?? $r2['convey_allow'] ?? 0);
        $epf               = (float)($r2['epf'] ?? 0);
        $esi               = (float)($r2['esi'] ?? 0);
        $travel_allow      = (float)($r2['travel_allow'] ?? 0);
        $two_wheeler_maint = (float)($r2['two_wheeler_maint'] ?? 0);
        $tds               = (float)($r2['tds'] ?? 0);
        $advance           = (float)($r2['advance'] ?? 0);
        $outstanding_amt   = (float)($r2['outstanding_amt'] ?? 0); // NEW

        // Only use user's basic_salary if payroll basic is empty/zero
        $payroll_basic_current = isset($r2['basic']) ? (float)$r2['basic'] : 0;
        if ($payroll_basic_current <= 0 &&
            isset($r2['user_basic_salary']) &&
            $r2['user_basic_salary'] !== null &&
            $r2['user_basic_salary'] !== '') {

            $ub = (float)$r2['user_basic_salary'];
            if ($ub > 0) {
                $basic = $ub;
                if (empty($salary) || $salary == 0.0) $salary = $ub;
            }
        }

        if ($working_days <= 0) {
            $working_days = ($paid_days + (float)($r2['absent_days'] ?? 0));
            if ($working_days <= 0) $working_days = 30;
        }

        $per_day_salary = $working_days > 0 ? round($salary / $working_days, 2) : 0;
        $total_wages    = round($per_day_salary * $paid_days, 2);
        if ($basic <= 0) $basic = $total_wages;
        $gross_salary = $basic + $da + $hra + $medical_allow + $conveyance_allow;
        $total        = $gross_salary + $travel_allow + $two_wheeler_maint;
        // include outstanding as addition to payable (owed to employee)
        $pending_amt  = $total + $outstanding_amt - $epf - $esi - $tds - $advance;
        $grand_total  = $pending_amt;

        $upd = $conn->prepare("UPDATE payroll SET salary = ?, per_day_salary = ?, total_wages = ?, basic = ?, gross_salary = ?, total = ?, pending_amt = ?, grand_total = ? WHERE id = ?");
        if ($upd) {
            if ($upd->bind_param("ddddddddi", $salary, $per_day_salary, $total_wages, $basic, $gross_salary, $total, $pending_amt, $grand_total, $id)) {
                if ($upd->execute()) {
                    $update_message = '<div class="alert alert-success">Payslip recomputed and saved.</div>';
                } else {
                    $update_message = '<div class="alert alert-danger">Failed to update payslip: ' . htmlspecialchars($upd->error) . '</div>';
                }
            } else {
                $update_message = '<div class="alert alert-danger">Bind failed: ' . htmlspecialchars($upd->error) . '</div>';
            }
            $upd->close();
        } else {
            $update_message = '<div class="alert alert-danger">Prepare failed: ' . htmlspecialchars($conn->error) . '</div>';
        }
    } else {
        $update_message = '<div class="alert alert-danger">Failed to fetch payroll for recompute.</div>';
    }

    // reload row
    $sql_reload = "SELECT {$select_cols} FROM payroll p LEFT JOIN users u ON p.emp_id = u.id WHERE p.id = ?";
    $stmt = $conn->prepare($sql_reload);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $stmt->close();

    // After reload: again, only fall back to user_basic_salary if payroll basic is empty
    $payroll_basic_current = isset($row['basic']) ? (float)$row['basic'] : 0;
    if ($payroll_basic_current <= 0 &&
        isset($row['user_basic_salary']) &&
        $row['user_basic_salary'] !== null &&
        $row['user_basic_salary'] !== '') {

        $ub = (float)$row['user_basic_salary'];
        if ($ub > 0) {
            $row['basic'] = $ub;
            if (empty($row['salary']) || (float)$row['salary'] == 0.0) $row['salary'] = $ub;
        }
    }

    // recompute local variables after reload
    $salary            = (float)($row['salary'] ?? 0);
    $working_days      = (float)($row['working_days'] ?? 0);
    $absent_days       = (float)($row['absent_days'] ?? 0);
    $paid_days         = (float)($row['paid_days'] ?? 0);
    $basic             = (float)($row['basic'] ?? 0);
    $da                = (float)($row['da'] ?? 0);
    $hra               = (float)($row['hra'] ?? 0);
    $medical_allow     = (float)($row['medical_allow'] ?? 0);
    $conveyance_allow  = (float)($row['conveyance_allow'] ?? 0);
    $epf               = (float)($row['epf'] ?? 0);
    $esi               = (float)($row['esi'] ?? 0);
    $travel_allow      = (float)($row['travel_allow'] ?? 0);
    $two_wheeler_maint = (float)($row['two_wheeler_maint'] ?? 0);
    $tds               = (float)($row['tds'] ?? 0);
    $advance           = (float)($row['advance'] ?? 0);
    $outstanding_amt   = (float)($row['outstanding_amt'] ?? 0);

    if ($working_days <= 0) {
        $working_days = $paid_days + $absent_days;
        if ($working_days <= 0) $working_days = 30;
    }
    $per_day_salary = $working_days > 0 ? round($salary / $working_days, 2) : 0;
    $total_wages    = round($per_day_salary * $paid_days, 2);
    if ($basic <= 0) $basic = $total_wages;
    $gross_salary = $basic + $da + $hra + $medical_allow + $conveyance_allow;
    $total        = $gross_salary + $travel_allow + $two_wheeler_maint;
    // again: add outstanding to payable
    $pending_amt  = $total + $outstanding_amt - $epf - $esi - $tds - $advance;
    $grand_total  = $pending_amt;
}

// helper
function nf($v){ return number_format((float)$v, 2); }

// company details
$company_name = "Arostar Enterprises Pvt Ltd";
$company_addr = "No:23,24,25 Arul Murugan Nagar, Pazhanthandalam Village, Thirumudivakkam, Chennai, Tamilnadu - 600132";
$company_pan  = "PAN: AALCA0811F";
$company_gst  = "GSTIN: 33AALCA0811F1Z9";
$company_email = "accounts@arostarint.com";
$company_phone = "Phone no: 04445574630";

// determine logo (use relative path if exists)
$logo_html = '';
$local_full_path = __DIR__ . DIRECTORY_SEPARATOR . $company_logo;
if (!empty($company_logo) && file_exists($local_full_path)) {
    $logo_html = htmlspecialchars($company_logo);
} elseif (!empty($company_logo_url)) {
    $logo_html = htmlspecialchars($company_logo_url);
}

// determine payslip month display
$payslip_month_display = htmlspecialchars(date('F Y', strtotime(($month ?? $row['month']).'-01')));
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Payslip - <?= htmlspecialchars($row['user_name'] ?? 'Employee') ?> - <?= $payslip_month_display ?></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
    /* A4 portrait single page print */
    @page { size: A4 portrait; margin: 10mm; }
    html, body { height: 100%; margin:0; padding:0; }
    body{ background:#fff; font-family: Arial, Helvetica, sans-serif; -webkit-print-color-adjust: exact; }
    .container { max-width: 210mm; margin:0 auto; padding:0; }
    .payslip {
        width: 100%;
        box-sizing: border-box;
        border: 1px solid #e2e2e2;
        padding: 10mm;
        border-radius: 4px;
        background: #fff;
        overflow: hidden;
        transform-origin: top left;
        -webkit-transform-origin: top left;
    }
    .payslip, .payslip * { font-size: 12px; }
    .company h2{ margin:0; font-size:16px; }
    .company small{ display:block; color:#666; font-size:11px; }
    .muted { color:#666; font-size:11px; }
    .right { text-align:right; }
    .company-logo { max-height:70px; margin-right:10px; display:inline-block; vertical-align:middle; }
    .company-header { display:flex; align-items:center; gap:10px; }
    .company-info { flex:1; }

    /* NEW: three-column info header */
    .info-3cols {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        gap: 10px;
        margin-top: 8px;
    }
    .info-card {
        padding: 8px;
        border-radius: 4px;
        background: #fafafa;
        border: 1px solid #f1f1f1;
    }
    .info-title { font-size:12px; font-weight:700; color:#333; margin-bottom:6px; }
    .info-row { display:flex; justify-content:space-between; padding:2px 0; font-size:12px; }
    .info-key { color:#666; font-weight:700; }
    .info-val { font-weight:600; text-align:right; }

    table.table { margin-bottom:0; font-size:12px; }
    td.right, th.right { text-align:right; }
    .table-light th { background:#f8f9fa; }
    .table-secondary td { font-weight:700; }
    .no-print { display:block; margin-top:8px; }
    @media print {
        @page { size: A4 portrait; margin: 6mm; }
        body, html { margin:0; padding:0; }
        .no-print { display:none !important; }
        .payslip { border: none; padding: 6mm; border-radius: 0; box-shadow: none; }
        .payslip, .payslip * { font-size: 11px; }
        .company-logo { max-height:60px; }
        .info-3cols { gap:6px; }
        .info-card { padding:6px; }
        table.table { font-size:11px; }
    }
    @media (max-width:767px) {
        .info-3cols { grid-template-columns: 1fr; }
        .company-logo { max-height:60px; }
    }
</style>
</head>
<body>
<div class="container">
    <div class="payslip shadow-sm" id="payslip-root">
        <div class="d-flex justify-content-between align-items-start mb-2">
            <div class="company-header" style="align-items:flex-start;">
                <?php if (!empty($logo_html)): ?>
                    <img src="<?= $logo_html ?>" alt="Company Logo" class="company-logo">
                <?php endif; ?>
                <div class="company-info">
                    <h2><?= htmlspecialchars($company_name) ?></h2>
                    <small><?= htmlspecialchars($company_addr) ?></small>
                    <small class="muted"><?= htmlspecialchars($company_pan) ?> | <?= htmlspecialchars($company_gst) ?></small>
                    <small class="muted"><?= htmlspecialchars($company_email) ?> | <?= htmlspecialchars($company_phone) ?></small>
                </div>
            </div>

            <div class="text-end">
                <h5 class="mb-1">Payslip</h5>
                <div class="muted"><?= $payslip_month_display ?></div>
            </div>
        </div>

        <?= $update_message ?>

        <!-- NEW: Three-column information area -->
        <div class="info-3cols" aria-label="Payslip information">
            <!-- Column 1: Employee Details -->
            <div class="info-card" role="region" aria-label="Employee details">
                <div class="info-title">Employee Details</div>
                <div class="info-row"><div class="info-key">Employee</div><div class="info-val"><?= htmlspecialchars($row['user_name'] ?? 'Employee') ?></div></div>
                <div class="info-row"><div class="info-key">Month</div><div class="info-val"><?= $payslip_month_display ?></div></div>
                <div class="info-row"><div class="info-key">Emp Code</div><div class="info-val"><?= htmlspecialchars($row['user_emp_code'] ?? ($row['emp_id'] ?? '')) ?></div></div>
                <div class="info-row"><div class="info-key">Division</div><div class="info-val"><?= htmlspecialchars($row['user_division'] ?? ($row['division'] ?? '')) ?></div></div>
                <div class="info-row"><div class="info-key">PF No</div><div class="info-val"><?= htmlspecialchars($row['user_pf'] ?? ($row['pf_no'] ?? '-')) ?></div></div>
                <div class="info-row"><div class="info-key">ESI No</div><div class="info-val"><?= htmlspecialchars($row['user_esi'] ?? ($row['esi_no'] ?? '-')) ?></div></div>
                <div class="info-row"><div class="info-key">UAN</div><div class="info-val"><?= htmlspecialchars($row['user_uan'] ?? '-') ?></div></div>
            </div>

            <!-- Column 2: Account Details -->
            <div class="info-card" role="region" aria-label="Account details">
                <div class="info-title">Account Details</div>
                <?php
                    $display_pay_mode = '-';
                    if (!empty($row['payment_mode'])) $display_pay_mode = $row['payment_mode'];
                    elseif (!empty($row['user_pay_mode'])) $display_pay_mode = $row['user_pay_mode'];
                    elseif (!empty($row['user_bank'])) $display_pay_mode = 'Bank';
                    else $display_pay_mode = 'Bank';
                ?>
                <div class="info-row"><div class="info-key">Pay Mode</div><div class="info-val"><?= htmlspecialchars($display_pay_mode) ?></div></div>
                <div class="info-row"><div class="info-key">Bank / A/C</div><div class="info-val"><?= htmlspecialchars($row['user_bank'] ?? '-') ?></div></div>
                <div class="info-row"><div class="info-key">IFSC</div><div class="info-val"><?= htmlspecialchars($row['user_ifsc'] ?? '-') ?></div></div>
                <?php if (!empty($row['user_bank']) || !empty($row['user_ifsc'])): ?>
                    <div class="info-row"><div class="info-key">Account Verified</div><div class="info-val"><?= (!empty($row['user_bank']) ? 'Yes' : 'No') ?></div></div>
                <?php endif; ?>
            </div>

            <!-- Column 3: Attendance / Payroll details -->
            <div class="info-card" role="region" aria-label="Attendance details">
                <div class="info-title">Attendance / Pay Summary</div>
                <div class="info-row"><div class="info-key">Salary</div><div class="info-val"><?= nf($salary) ?></div></div>
                <div class="info-row"><div class="info-key">Working days</div><div class="info-val"><?= nf($working_days) ?></div></div>
                <div class="info-row"><div class="info-key">Absent</div><div class="info-val"><?= nf($absent_days) ?></div></div>
                <div class="info-row"><div class="info-key">Paid days</div><div class="info-val"><?= nf($paid_days) ?></div></div>
                <div class="info-row"><div class="info-key">Per day</div><div class="info-val"><?= nf($per_day_salary) ?></div></div>
                <div class="info-row"><div class="info-key">Total wages</div><div class="info-val"><?= nf($total_wages) ?></div></div>
                <div class="info-row"><div class="info-key">Outstanding (owed to emp)</div><div class="info-val"><?= nf($outstanding_amt) ?></div></div>
            </div>
        </div>

        <hr style="margin:12px 0; border-color:#eee;">

        <!-- Earnings / Deductions table -->
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="table-light">
                    <tr>
                        <th>Earnings</th>
                        <th class="right">Amount (INR)</th>
                        <th>Deductions</th>
                        <th class="right">Amount (INR)</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Basic</td>
                        <td class="right"><?= nf($basic) ?></td>
                        <td>EPF</td>
                        <td class="right"><?= nf($epf) ?></td>
                    </tr>
                    <tr>
                        <td>DA</td>
                        <td class="right"><?= nf($da) ?></td>
                        <td>ESI</td>
                        <td class="right"><?= nf($esi) ?></td>
                    </tr>
                    <tr>
                        <td>HRA</td>
                        <td class="right"><?= nf($hra) ?></td>
                        <td>TDS</td>
                        <td class="right"><?= nf($tds) ?></td>
                    </tr>
                    <tr>
                        <td>Medical Allow</td>
                        <td class="right"><?= nf($medical_allow) ?></td>
                        <td>Advance</td>
                        <td class="right"><?= nf($advance) ?></td>
                    </tr>
                    <!-- Outstanding moved to earnings/adjustments -->
                    <tr>
                        <td>Conveyance Allow</td>
                        <td class="right"><?= nf($conveyance_allow) ?></td>
                        <td></td>
                        <td></td>
                    </tr>

                    <tr class="table-secondary">
                        <td><strong>Gross Salary</strong></td>
                        <td class="right"><strong><?= nf($gross_salary) ?></strong></td>
                        <!-- Total Deductions excludes outstanding (since outstanding is owed to emp and added to earnings) -->
                        <td><strong>Total Deductions</strong></td>
                        <td class="right"><strong><?= nf($epf + $esi + $tds + $advance) ?></strong></td>
                    </tr>

                    <tr>
                        <td>Travel Allow</td>
                        <td class="right"><?= nf($travel_allow) ?></td>
                        <td>Two Wheeler Maintenance</td>
                        <td class="right"><?= nf($two_wheeler_maint) ?></td>
                    </tr>

                    <tr>
                        <td><strong>Adjustments (Outstanding)</strong></td>
                        <td class="right"><strong><?= nf($outstanding_amt) ?></strong></td>
                        <td></td>
                        <td></td>
                    </tr>

                    <tr class="table-light">
                        <td><strong>Total Earnings</strong></td>
                        <!-- Total earnings now = total (gross + other) + outstanding_amt -->
                        <td class="right"><strong><?= nf($total + $outstanding_amt) ?></strong></td>
                        <td><strong>Net Payable</strong></td>
                        <td class="right"><strong><?= nf($grand_total) ?></strong></td>
                    </tr>
                </tbody>
            </table>
        </div>

        <footer style="margin-top:20px; text-align:center; width:100%;">
            <div class="muted" style="font-size:12px; text-align:center;">
                <strong>This is a computer generated payslip. No signature required.</strong>
            </div>
        </footer>
    </div>

    <div class="d-flex justify-content-between align-items-center mt-3 no-print">
        <div>
            <?php if ($is_admin && $id > 0): ?>
                <form method="post" style="display:inline;">
                    <input type="hidden" name="id" value="<?= htmlspecialchars($id) ?>">
                    <?php if ($month): ?>
                        <input type="hidden" name="month" value="<?= htmlspecialchars($month) ?>">
                    <?php endif; ?>
                    <button type="submit" name="recreate_payslip" class="btn btn-sm btn-outline-danger" onclick="return confirm('Recreate payslip calculations for this employee?');">
                        <i class="bi bi-arrow-repeat"></i> Recreate Payslip
                    </button>
                </form>
            <?php endif; ?>
        </div>
        <div>
            <button id="printBtn" onclick="window.print();" class="btn btn-sm btn-warning"><i class="bi bi-printer"></i> Print</button>
            <a href="payroll.php?month=<?= htmlspecialchars($month ?? ($row['month'] ?? '')) ?>" class="btn btn-sm btn-secondary">Back</a>
        </div>
    </div>
</div>

<!-- bootstrap icons (used in buttons) -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

<!-- Auto-scale script: computes a scale so .payslip fits one A4 page -->
<script>
(function(){
  var rootSelector = '.payslip';
  function computeAndApplyScale() {
    var el = document.querySelector(rootSelector);
    if (!el) return;
    el.style.transform = 'none';
    el.style.webkitTransform = 'none';

    var tmp = document.createElement('div');
    tmp.style.position = 'absolute';
    tmp.style.visibility = 'hidden';
    tmp.style.height = '297mm';
    tmp.style.width = '210mm';
    tmp.style.top = '-9999px';
    document.body.appendChild(tmp);
    var pageH = tmp.getBoundingClientRect().height;
    var pageW = tmp.getBoundingClientRect().width;
    document.body.removeChild(tmp);

    var elRect = el.getBoundingClientRect();
    var elH = elRect.height;
    var elW = elRect.width;

    var scale = Math.min(pageW / elW, pageH / elH, 1);
    scale = Math.round(scale * 1000) / 1000;

    el.style.transform = 'scale(' + scale + ')';
    el.style.webkitTransform = 'scale(' + scale + ')';
  }

  if (window.matchMedia) {
    window.addEventListener('beforeprint', computeAndApplyScale);
    window.addEventListener('afterprint', function() {
      var el = document.querySelector(rootSelector);
      if (el) { el.style.transform = 'none'; el.style.webkitTransform = 'none'; }
    });
  } else {
    window.onbeforeprint = computeAndApplyScale;
    window.onafterprint = function(){ var el = document.querySelector(rootSelector); if (el) el.style.transform = 'none'; };
  }

  document.addEventListener('DOMContentLoaded', function(){
    setTimeout(function(){ computeAndApplyScale(); }, 100);
  });

  document.getElementById('printBtn') && document.getElementById('printBtn').addEventListener('click', function(){
    computeAndApplyScale();
    setTimeout(function(){}, 50);
  });

})();
</script>

</body>
</html>
