<?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';
require_once __DIR__ . '/includes/module_helpers.php';

$context = payroll_org_context($conn);
$flashMessage = $_SESSION['flash_ok'] ?? '';
$flashError = $_SESSION['flash_err'] ?? '';
unset($_SESSION['flash_ok'], $_SESSION['flash_err']);

$requiredTables = ['giving_campaigns'];
$missingTables = payroll_missing_tables($conn, $requiredTables);
$schemaReady = empty($missingTables);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$schemaReady) {
    payroll_redirect_with_flash('giving.php', 'Import database/workhub_modules.sql in phpMyAdmin before using Giving.', true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_campaign'])) {
    $campaignName = trim((string) ($_POST['campaign_name'] ?? ''));
    $aboutCampaign = trim((string) ($_POST['about_campaign'] ?? ''));
    $exemptionType = trim((string) ($_POST['exemption_type'] ?? ''));
    $campaignEndsOn = trim((string) ($_POST['campaign_ends_on'] ?? ''));
    $showInPortal = isset($_POST['show_in_portal']) ? 1 : 0;

    if ($campaignName === '' || $aboutCampaign === '' || $exemptionType === '' || $campaignEndsOn === '') {
        payroll_redirect_with_flash('giving.php?view=new', 'All campaign fields except portal visibility are required.', true);
    }

    $campaignEndDate = $campaignEndsOn . '-01';
    $endTimestamp = strtotime($campaignEndDate);
    $status = ($endTimestamp && $endTimestamp < strtotime(date('Y-m-01'))) ? 'completed' : 'active';

    $stmt = $conn->prepare("INSERT INTO giving_campaigns (org_id, campaign_name, about_campaign, exemption_type, campaign_ends_on, show_in_portal, status)
                            VALUES (?, ?, ?, ?, ?, ?, ?)");
    if (!$stmt) {
        payroll_redirect_with_flash('giving.php?view=new', 'Unable to prepare campaign save.', true);
    }

    $stmt->bind_param('sssssis', $context['org_id'], $campaignName, $aboutCampaign, $exemptionType, $campaignEndDate, $showInPortal, $status);
    if (!$stmt->execute()) {
        $message = 'Unable to save campaign. ' . $stmt->error;
        $stmt->close();
        payroll_redirect_with_flash('giving.php?view=new', $message, true);
    }
    $stmt->close();

    payroll_redirect_with_flash('giving.php', 'Campaign created successfully.');
}

$view = trim((string) ($_GET['view'] ?? 'list'));
$validViews = ['list', 'new'];
if (!in_array($view, $validViews, true)) {
    $view = 'list';
}

$statusFilter = trim((string) ($_GET['status'] ?? 'active'));
$validStatuses = ['all', 'active', 'completed'];
if (!in_array($statusFilter, $validStatuses, true)) {
    $statusFilter = 'active';
}

$campaigns = [];
if ($schemaReady) {
    $campaignSql = "SELECT * FROM giving_campaigns WHERE org_id = ?";
    $bindTypes = 's';
    $bindValues = [$context['org_id']];

    if ($statusFilter !== 'all') {
        $campaignSql .= " AND status = ?";
        $bindTypes .= 's';
        $bindValues[] = $statusFilter;
    }

    $campaignSql .= " ORDER BY campaign_ends_on DESC, id DESC";
    $stmt = $conn->prepare($campaignSql);
    if ($stmt) {
        $bind = [$bindTypes];
        foreach ($bindValues as $index => $value) {
            $bindValues[$index] = $value;
            $bind[] = &$bindValues[$index];
        }
        call_user_func_array([$stmt, 'bind_param'], $bind);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $campaigns[] = $row;
        }
        $stmt->close();
    }
}

$selectedStatusLabel = [
    'all' => 'All Campaigns',
    'active' => 'Active Campaigns',
    'completed' => 'Completed Campaigns',
][$statusFilter];

$emptyTitle = [
    'all' => 'There are no campaigns',
    'active' => 'There are no active campaigns',
    'completed' => 'There are no completed campaigns',
][$statusFilter];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Giving | Payroll</title>
    <link rel="stylesheet" href="dashboard.css">
    <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
    <link rel="stylesheet" href="assets/font-inter.css">
    <link rel="stylesheet" href="modules.css">
</head>
<body class="module-page">
<div class="module-shell loans-shell">
    <aside class="module-sidebar">
        <div class="module-brand">
            <img src="images/b2l_mobitech_pvt_ltd_logo.jpg" alt="B2L Mobitech Pvt Ltd">
            <span>Payroll</span>
        </div>
        <div class="module-sidebar-scroll">
            <div class="module-sidebar-section">
                <div class="module-getting-started">
                    <div class="module-gs-top">
                        <i class="fa-solid fa-wand-magic-sparkles"></i>
                        <span>Getting Started</span>
                    </div>
                    <div class="module-progress-bar">
                        <div class="module-progress-fill"></div>
                    </div>
                </div>
            </div>
            <nav class="module-nav">
                <a href="dashboard.php"><i class="fa-regular fa-circle-dot"></i><span>Dashboard</span></a>
                <a href="employees.php"><i class="fa-regular fa-user"></i><span>Employees</span></a>
                <a href="payruns.php"><i class="fa-regular fa-calendar-check"></i><span>Pay Runs</span></a>
                <a href="#"><i class="fa-regular fa-square-check"></i><span>Approvals</span></a>
                <a href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a>
                <a href="loans.php"><i class="fa-solid fa-indian-rupee-sign"></i><span>Loans</span></a>
                <a class="active" href="giving.php"><i class="fa-regular fa-heart"></i><span>Giving</span></a>
                <a href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a>
                <a href="reports.php"><i class="fa-regular fa-chart-bar"></i><span>Reports</span></a>
                <a href="settings.php"><i class="fa-solid fa-gear"></i><span>Settings</span></a>
            </nav>
        </div>
        <div class="module-sidebar-footer">
            <a class="module-support-link" href="#">Contact Support <i class="fa-solid fa-angle-right"></i></a>
        </div>
        <div class="module-support-tile">
            <div class="module-support-title">Track TDS Liabilities and Generate Form 24Q</div>
            <a class="module-support-action" href="#">View Details</a>
        </div>
    </aside>

    <main class="module-main loans-main">
        <div class="module-topbar loans-topbar">
            <div class="module-search">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="text" placeholder="Search in Employee">
            </div>
            <div class="module-user">
                <span><?php echo htmlspecialchars($context['display_name']); ?></span>
                <span class="module-avatar"><?php echo htmlspecialchars(strtoupper(substr($context['display_name'], 0, 1))); ?></span>
            </div>
        </div>

        <?php if ($flashMessage): ?>
            <div class="alert ok"><?php echo htmlspecialchars($flashMessage); ?></div>
        <?php endif; ?>
        <?php if ($flashError): ?>
            <div class="alert err"><?php echo htmlspecialchars($flashError); ?></div>
        <?php endif; ?>
        <?php if (!$schemaReady): ?>
            <div class="alert err">Missing tables: <?php echo htmlspecialchars(implode(', ', $missingTables)); ?>. Import <strong>database/workhub_modules.sql</strong> in phpMyAdmin first.</div>
        <?php endif; ?>

        <?php if ($view === 'new'): ?>
            <section class="loan-page loan-form-page giving-form-page">
                <div class="loan-page-head">
                    <h1>New Campaign</h1>
                    <a class="icon-btn ghost" href="giving.php?status=<?php echo urlencode($statusFilter); ?>" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                </div>

                <form method="post" class="loan-create-form giving-create-form">
                    <input type="hidden" name="create_campaign" value="1">

                    <div class="field-group full giving-field-row">
                        <label for="campaign_name">Campaign Name <span class="req">*</span></label>
                        <input id="campaign_name" type="text" name="campaign_name" placeholder="Education Support Drive" required>
                    </div>

                    <div class="field-group full giving-field-row">
                        <label for="about_campaign">About the Campaign <span class="req">*</span></label>
                        <textarea id="about_campaign" name="about_campaign" placeholder="Describe the purpose and how contributions will be used" required></textarea>
                    </div>

                    <div class="field-group full giving-field-row">
                        <label for="exemption_type">Exemption Type <span class="req">*</span></label>
                        <select id="exemption_type" name="exemption_type" required>
                            <option value="">Select</option>
                            <option value="80G">80G</option>
                            <option value="80GGA">80GGA</option>
                            <option value="CSR">CSR</option>
                        </select>
                    </div>

                    <div class="field-group giving-field-row giving-date-field">
                        <label for="campaign_ends_on">Campaign Ends on <span class="req">*</span></label>
                        <input id="campaign_ends_on" type="month" name="campaign_ends_on" required>
                    </div>

                    <div class="field-group full giving-checkbox-row">
                        <label class="giving-checkbox-label" for="show_in_portal">
                            <input id="show_in_portal" type="checkbox" name="show_in_portal" value="1">
                            <span>Show in Employee Portal</span>
                        </label>
                    </div>

                    <div class="giving-note-card">
                        <div class="giving-note-head">
                            <i class="fa-solid fa-circle-info"></i>
                            <span>Things to Note</span>
                        </div>
                        <p>All contributions made by your employees will be considered for exemptions based on the exemption type selected and will be applied in their Income Tax calculations and Form 16.</p>
                        <p>Based on your employees' contribution, liability will be raised, and you can pay the amount deducted using their PAN.</p>
                    </div>

                    <div class="form-actions footer-actions">
                        <button class="btn-primary" type="submit">Save</button>
                        <a class="btn-secondary" href="giving.php?status=<?php echo urlencode($statusFilter); ?>">Cancel</a>
                        <div class="mand-note"><span>*</span> indicates mandatory fields</div>
                    </div>
                </form>
            </section>
        <?php else: ?>
            <section class="loan-page giving-page">
                <div class="loan-toolbar">
                    <div class="loan-status-dropdown">
                        <button class="status-chip" type="button" data-status-toggle>
                            <span><?php echo htmlspecialchars($selectedStatusLabel); ?></span>
                            <i class="fa-solid fa-angle-down"></i>
                        </button>
                        <div class="status-menu" data-status-menu>
                            <a class="<?php echo $statusFilter === 'all' ? 'active' : ''; ?>" href="giving.php?status=all">All Campaigns</a>
                            <a class="<?php echo $statusFilter === 'active' ? 'active' : ''; ?>" href="giving.php?status=active">Active Campaigns</a>
                            <a class="<?php echo $statusFilter === 'completed' ? 'active' : ''; ?>" href="giving.php?status=completed">Completed Campaigns</a>
                        </div>
                    </div>

                    <div class="loan-actions">
                        <a class="btn-primary compact" href="giving.php?view=new&status=<?php echo urlencode($statusFilter); ?>"><i class="fa-solid fa-plus"></i> New</a>
                    </div>
                </div>

                <?php if (!$campaigns): ?>
                    <div class="empty-state giving-empty-state">
                        <div class="empty-illustration giving-box">
                            <div class="giving-box-back"></div>
                            <div class="giving-box-front"></div>
                            <div class="giving-heart"><i class="fa-solid fa-heart"></i></div>
                            <div class="giving-coin"><i class="fa-solid fa-indian-rupee-sign"></i></div>
                        </div>
                        <p class="giving-empty-title"><?php echo htmlspecialchars($emptyTitle); ?></p>
                        <p class="giving-empty-copy">Create campaigns to allow your employees to contribute for a cause.</p>
                        <a class="btn-primary compact" href="giving.php?view=new&status=<?php echo urlencode($statusFilter); ?>">New Campaign</a>
                    </div>
                <?php else: ?>
                    <div class="giving-list-shell">
                        <div class="table-wrap loan-table-wrap">
                            <table class="module-table">
                                <thead>
                                <tr>
                                    <th>Campaign</th>
                                    <th>Exemption Type</th>
                                    <th>Campaign Ends On</th>
                                    <th>Employee Portal</th>
                                    <th>Status</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($campaigns as $campaign): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars((string) $campaign['campaign_name']); ?></strong><br>
                                            <span class="muted"><?php echo htmlspecialchars((string) $campaign['about_campaign']); ?></span>
                                        </td>
                                        <td><?php echo htmlspecialchars((string) $campaign['exemption_type']); ?></td>
                                        <td><?php echo htmlspecialchars(payroll_month_label($campaign['campaign_ends_on'] ?? null)); ?></td>
                                        <td><?php echo !empty($campaign['show_in_portal']) ? 'Shown' : 'Hidden'; ?></td>
                                        <td><span class="badge <?php echo htmlspecialchars((string) $campaign['status']); ?>"><?php echo htmlspecialchars(ucfirst((string) $campaign['status'])); ?></span></td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
            </section>
        <?php endif; ?>
    </main>
</div>

<script>
    (function () {
        const statusBtn = document.querySelector('[data-status-toggle]');
        const statusMenu = document.querySelector('[data-status-menu]');
        if (!statusBtn || !statusMenu) return;
        statusBtn.addEventListener('click', function (event) {
            event.stopPropagation();
            statusMenu.classList.toggle('open');
        });
        document.addEventListener('click', function (event) {
            if (!statusMenu.contains(event.target) && !statusBtn.contains(event.target)) {
                statusMenu.classList.remove('open');
            }
        });
    })();
</script>
</body>
</html>
