<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';

session_start();
if (empty($_SESSION['authenticated'])) {
    header("Location: signin.php");
    exit();
}
require_once __DIR__ . '/db.php';

$result = $conn->query("SELECT * FROM organizations ORDER BY id DESC LIMIT 1");
$row = $result ? $result->fetch_assoc() : null;
$orgName = $_SESSION['org_name'] ?? ($row['organisation_name'] ?? 'demo');
$trialStatus = strtoupper($_SESSION['org_status'] ?? ($row['status'] ?? 'TRIAL'));

$payrunErrors = [];
$payrunSuccess = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['payrun_action'])) {
    $action = $_POST['payrun_action'];
    if ($action === 'one_time') {
        $component = trim((string)($_POST['component'] ?? ''));
        $payDate = trim((string)($_POST['pay_date'] ?? ''));
        if ($component === '') {
            $payrunErrors[] = 'Select a one time component.';
        }
        if ($payDate === '') {
            $payrunErrors[] = 'Enter a pay date.';
        }
        if (!$payrunErrors) {
            $stmt = $conn->prepare("INSERT INTO payruns (org_id, pay_type, component, pay_date, status) VALUES (?, 'one_time', ?, ?, 'draft')");
            if ($stmt) {
                $stmt->bind_param('sss', $orgName, $component, $payDate);
                if ($stmt->execute()) {
                    $payrunSuccess = 'One time payrun saved.';
                } else {
                    $payrunErrors[] = 'Unable to save payrun.';
                }
                $stmt->close();
            } else {
                $payrunErrors[] = 'Unable to prepare payrun save.';
            }
        }
    } elseif ($action === 'off_cycle') {
        $payDate = trim((string)($_POST['pay_date'] ?? ''));
        if ($payDate === '') {
            $payrunErrors[] = 'Enter a pay date.';
        }
        if (!$payrunErrors) {
            $stmt = $conn->prepare("INSERT INTO payruns (org_id, pay_type, component, pay_date, status) VALUES (?, 'off_cycle', NULL, ?, 'draft')");
            if ($stmt) {
                $stmt->bind_param('ss', $orgName, $payDate);
                if ($stmt->execute()) {
                    $payrunSuccess = 'Off cycle payrun saved.';
                } else {
                    $payrunErrors[] = 'Unable to save payrun.';
                }
                $stmt->close();
            } else {
                $payrunErrors[] = 'Unable to prepare payrun save.';
            }
        }
    }
}

$payruns = [];
$historyResult = $conn->query("SELECT id, pay_type, component, pay_date, status FROM payruns WHERE org_id = '" . $conn->real_escape_string($orgName) . "' ORDER BY id DESC");
if ($historyResult) {
    while ($row = $historyResult->fetch_assoc()) {
        $payruns[] = $row;
    }
}
$latestPayrun = $payruns[0] ?? null;
$latestTitle = 'Process Pay Run for May 2025';
$latestPayDate = '30/05/2025';
if ($latestPayrun && !empty($latestPayrun['pay_date'])) {
    $dt = DateTime::createFromFormat('Y-m-d', $latestPayrun['pay_date']);
    if ($dt) {
        $latestTitle = 'Process Pay Run for ' . $dt->format('F Y');
        $latestPayDate = $dt->format('d/m/Y');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pay Runs</title>
    <link rel="stylesheet" href="dashboard.css">
    <link rel="stylesheet" href="payruns.css">
    <link rel="stylesheet" href="assets/font-inter.css">
    <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
</head>
<body class="dash-page">
<div class="dash-layout">
    <aside class="dash-sidebar">
        <div class="sidebar-brand">
            <img src="images/b2l_mobitech_pvt_ltd_logo.jpg" class="logo" alt="B2L Mobitech Pvt Ltd">
        </div>
        <div class="sidebar-scroll">
            <div class="sidebar-section">
                <div class="getting-started">
                    <div class="gs-top">
                        <i class="fa-solid fa-rocket-launch"></i>
                        <span>Getting Started</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill"></div>
                    </div>
                </div>
            </div>
            <nav class="sidebar-nav">
                <a class="nav-item" href="dashboard.php"><i class="fa-solid fa-gauge-high"></i><span>Dashboard</span></a>
                <a class="nav-item" href="employees.php"><i class="fa-solid fa-users"></i><span>Employees</span></a>
                <a class="nav-item active" href="payruns.php"><i class="fa-solid fa-money-bill-wave"></i><span>Pay Runs</span></a>
                <div class="nav-group">
                    <button class="nav-item btn" type="button" data-nav-toggle><i class="fa-regular fa-square-check"></i><span>Approvals</span></button>
                    <div class="nav-sub">
                        <a class="nav-sub-item" href="reimbursements.php">Reimbursements</a>
                        <a class="nav-sub-item" href="proof_of_investments.php">Proof Of Investments</a>
                        <a class="nav-sub-item" href="salary_revision.php">Salary Revision</a>
                    </div>
                </div>
                <a class="nav-item" href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a>
                <a class="nav-item" href="loans.php"><i class="fa-solid fa-hand-holding-dollar"></i><span>Loans</span></a>
                <a class="nav-item" href="giving.php"><i class="fa-solid fa-gift"></i><span>Giving</span></a>
                <a class="nav-item" href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a>
                <a class="nav-item" href="reports.php"><i class="fa-solid fa-chart-pie"></i><span>Reports</span></a>
                <a class="nav-item" href="settings.php"><i class="fa-solid fa-gear"></i><span>Settings</span></a>
            </nav>
        </div>
        <div class="sidebar-footer">
            <a class="support-link" href="support.php">Contact Support</a>
        </div>
        <div class="support-tile">
            <div class="support-title">Track TDS Liabilities and Generate Form 24Q</div>
            <a class="support-action" href="support.php?promo=tds">View Details</a>
        </div>
    </aside>

    <main class="dash-main">
        <header class="dash-topbar">
            <div class="search-box">
                <i class="fa-solid fa-magnifying-glass search-icon"></i>
                <input type="text" placeholder="Search in Employee">
            </div>
            <div class="topbar-actions">
                <span class="trial">Your trial expires in 1 day(s). <a href="dashboard.php?modal=upgrade" class="upgrade-link">Upgrade</a></span>
                <a class="pill ghost org-toggle" href="dashboard.php?drawer=org"><span class="pill-label"><?php echo htmlspecialchars($orgName); ?></span><i class="fa-solid fa-angle-down"></i></a>
                <a class="top-icon icon-btn" href="dashboard.php?drawer=notif"><i class="fa-regular fa-bell"></i></a>
                <a class="top-icon top-link" href="settings.php"><i class="fa-solid fa-gear"></i></a>
                <a class="top-icon icon-btn" href="dashboard.php?drawer=apps"><i class="fa-solid fa-table-cells-large"></i></a>
                <span class="avatar"><?php echo strtoupper(substr($orgName, 0, 1)); ?></span>
            </div>
        </header>

        <section class="dash-content payruns-page">
            <div class="payruns-head">
                <div class="payruns-tabs" role="tablist">
                    <button class="pay-tab active" type="button" data-tab="run">Run Payroll</button>
                    <button class="pay-tab" type="button" data-tab="history">Payroll History</button>
                </div>
                <div class="payruns-actions">
                    <div class="dropdown">
                        <button class="btn-new" type="button" data-toggle="newMenu">
                            <i class="fa-solid fa-plus"></i> New <i class="fa-solid fa-angle-down"></i>
                        </button>
                        <div class="dropdown-menu" id="newMenu" aria-hidden="true">
                            <button type="button" data-open-modal="oneTime">One Time Payout</button>
                            <button type="button" data-open-modal="offCycle">Off Cycle Payrun</button>
                        </div>
                    </div>
                    <button class="btn-icon help-btn" type="button">?</button>
                </div>
            </div>

            <div class="payruns-panel" data-panel="run">
                <?php if ($payrunSuccess): ?>
                    <div class="alert-ok"><?php echo htmlspecialchars($payrunSuccess); ?></div>
                <?php endif; ?>
                <?php if (!empty($payrunErrors)): ?>
                    <div class="alert-err">
                        <div class="alert-err-title">Please fix the following:</div>
                        <ul>
                            <?php foreach ($payrunErrors as $err): ?>
                                <li><?php echo htmlspecialchars($err); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>
                <div class="pay-info">
                    <i class="fa-solid fa-wand-magic-sparkles"></i>
                    <div>Pay salaries from any bank account without switching to your bank portal using Payouts by B2L Payments.</div>
                    <a href="direct_deposits.php">Setup Payout</a>
                </div>

                <div class="payrun-card">
                    <div class="payrun-title"><?php echo htmlspecialchars($latestTitle); ?></div>
                    <div class="payrun-grid">
                        <div>
                            <div class="pay-label">Employees' Net Pay</div>
                            <div class="pay-value">YET TO PROCESS</div>
                        </div>
                        <div>
                            <div class="pay-label">Payment Date</div>
                            <div class="pay-value"><?php echo htmlspecialchars($latestPayDate); ?></div>
                        </div>
                        <div>
                            <div class="pay-label">No. of Employees</div>
                            <div class="pay-value">0</div>
                        </div>
                        <div class="payrun-cta">
                            <button class="btn-primary" type="button" disabled>CREATE PAY RUN</button>
                        </div>
                    </div>
                    <div class="payrun-note">
                        <i class="fa-regular fa-circle-info"></i>
                        There are no employees with completed profiles in this payroll. Please complete their profile to process this payrun.
                    </div>
                </div>
            </div>

            <div class="payruns-panel" data-panel="history" hidden>
                <div class="history-bar">
                    <div class="filter-group">
                        <label class="filter-label">Payroll Type:</label>
                        <button class="filter-btn" type="button" data-toggle="payTypeMenu">
                            <span>All</span>
                            <i class="fa-solid fa-angle-down"></i>
                        </button>
                        <div class="dropdown-menu wide" id="payTypeMenu" aria-hidden="true">
                            <div class="dropdown-search">
                                <i class="fa-solid fa-magnifying-glass"></i>
                                <input type="text" placeholder="Search">
                            </div>
                            <button type="button">Regular Payroll</button>
                            <button type="button">One Time Payout</button>
                            <button type="button">Off Cycle Payroll</button>
                        </div>
                    </div>
                    <button class="btn-icon filter-icon" type="button"><i class="fa-solid fa-filter"></i></button>
                </div>

                <?php if (empty($payruns)): ?>
                    <div class="history-empty">
                        <div class="history-illus">
                            <div class="illus-person"></div>
                            <div class="illus-sheet">
                                <div class="illus-line"></div>
                                <div class="illus-line short"></div>
                                <div class="illus-line"></div>
                            </div>
                        </div>
                        <div class="history-text">You don't have any pay runs for the filter applied</div>
                    </div>
                <?php else: ?>
                    <div class="history-table">
                        <div class="history-row head">
                            <div>Type</div>
                            <div>Component</div>
                            <div>Pay Date</div>
                            <div>Status</div>
                        </div>
                        <?php foreach ($payruns as $run): ?>
                            <div class="history-row">
                                <div><?php echo $run['pay_type'] === 'one_time' ? 'One Time Payout' : 'Off Cycle Payrun'; ?></div>
                                <div><?php echo htmlspecialchars($run['component'] ?? '-'); ?></div>
                                <div><?php echo htmlspecialchars($run['pay_date']); ?></div>
                                <div><span class="status-pill"><?php echo htmlspecialchars($run['status']); ?></span></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </section>
    </main>
</div>

<div class="modal" id="modalOneTime" aria-hidden="true">
    <div class="modal-backdrop" data-close-modal></div>
    <div class="modal-card">
        <div class="modal-head">
            <h3>Create One Time Payrun</h3>
            <button class="modal-close" type="button" data-close-modal><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST">
        <input type="hidden" name="payrun_action" value="one_time">
        <div class="modal-body">
            <label class="modal-label">Select One Time Component <span>*</span></label>
            <select class="modal-input" name="component" required>
                <option>Select</option>
                <option>Bonus</option>
                <option>Allowance</option>
                <option>Reimbursement</option>
            </select>
            <label class="modal-label">When would you like to pay? <span>*</span></label>
            <input class="modal-input" type="date" name="pay_date" required>
        </div>
        <div class="modal-actions">
            <button class="btn-primary" type="submit">Save and Continue</button>
            <button class="btn-outline" type="button" data-close-modal>Cancel</button>
        </div>
        </form>
    </div>
</div>

<div class="modal" id="modalOffCycle" aria-hidden="true">
    <div class="modal-backdrop" data-close-modal></div>
    <div class="modal-card">
        <div class="modal-head">
            <h3>Initiate Off Cycle Pay Run</h3>
            <button class="modal-close" type="button" data-close-modal><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST">
        <input type="hidden" name="payrun_action" value="off_cycle">
        <div class="modal-body">
            <label class="modal-label">When would you like to pay? <span>*</span></label>
            <input class="modal-input" type="date" name="pay_date" required>
        </div>
        <div class="modal-actions">
            <button class="btn-primary" type="submit">Save and Continue</button>
            <button class="btn-outline" type="button" data-close-modal>Cancel</button>
        </div>
        </form>
    </div>
</div>

<script>
    (function(){
        const tabs = document.querySelectorAll('.pay-tab');
        const panels = document.querySelectorAll('.payruns-panel');
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                const target = tab.getAttribute('data-tab');
                panels.forEach(panel => {
                    panel.hidden = panel.getAttribute('data-panel') !== target;
                });
            });
        });
    })();

    (function(){
        const toggleButtons = document.querySelectorAll('[data-toggle]');
        toggleButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                const menuId = btn.getAttribute('data-toggle');
                const menu = document.getElementById(menuId);
                if (!menu) return;
                const willOpen = menu.getAttribute('aria-hidden') === 'true';
                document.querySelectorAll('.dropdown-menu').forEach(m => m.setAttribute('aria-hidden', 'true'));
                menu.setAttribute('aria-hidden', willOpen ? 'false' : 'true');
                e.stopPropagation();
            });
        });
        document.addEventListener('click', () => {
            document.querySelectorAll('.dropdown-menu').forEach(m => m.setAttribute('aria-hidden', 'true'));
        });
    })();

    (function(){
        const modals = {
            oneTime: document.getElementById('modalOneTime'),
            offCycle: document.getElementById('modalOffCycle')
        };
        document.querySelectorAll('[data-open-modal]').forEach(btn => {
            btn.addEventListener('click', () => {
                const key = btn.getAttribute('data-open-modal');
                const modal = modals[key];
                if (modal) {
                    modal.setAttribute('aria-hidden', 'false');
                    document.body.classList.add('modal-open');
                }
            });
        });
        document.querySelectorAll('[data-close-modal]').forEach(btn => {
            btn.addEventListener('click', () => {
                document.querySelectorAll('.modal').forEach(modal => modal.setAttribute('aria-hidden', 'true'));
                document.body.classList.remove('modal-open');
            });
        });
    })();
</script>
<script>
  (function(){
    const toggles = document.querySelectorAll('[data-nav-toggle]');
    toggles.forEach(btn => {
      btn.addEventListener('click', () => {
        const group = btn.closest('.nav-group');
        if (!group) return;
        group.classList.toggle('open');
      });
    });
  })();
</script>
</body>
</html>

