<?php

require_once __DIR__ . '/Include/Config.php';
require_once __DIR__ . '/Include/PageInit.php';

use ChurchCRM\Authentication\AuthenticationManager;
use ChurchCRM\model\ChurchCRM\DonatedItemQuery;
use ChurchCRM\model\ChurchCRM\FundRaiser;
use ChurchCRM\model\ChurchCRM\FundRaiserQuery;
use ChurchCRM\model\ChurchCRM\PersonQuery;
use ChurchCRM\Utils\DateTimeUtils;
use ChurchCRM\Utils\InputUtils;
use ChurchCRM\Utils\RedirectUtils;
use ChurchCRM\view\PageHeader;

$sPageTitle = gettext('Create New Fund Raiser');

// Check if linkBack was explicitly provided (not the fallback)
$linkBackProvided = isset($_GET['linkBack']) && $_GET['linkBack'] !== '';
$linkBack = RedirectUtils::getLinkBackFromRequest('FindFundRaiser.php');
$iFundRaiserID = InputUtils::legacyFilterInputArr($_GET, 'FundRaiserID', 'int');

$fundraiser = null;
if ($iFundRaiserID > 0) {
    // Get the current fundraiser record
    $fundraiser = FundRaiserQuery::create()->findOneById($iFundRaiserID);
    $sPageTitle = gettext('Fundraiser') . ' #' . $iFundRaiserID . ' ' . $fundraiser->getTitle();
    // Set current fundraiser
    $_SESSION['iCurrentFundraiser'] = $iFundRaiserID;
}
$sPageSubtitle = gettext('Set up a new fundraiser campaign or event');

$sDateError = '';

// Is this the second pass?
if (isset($_POST['FundRaiserSubmit'])) {
    //Get all the variables from the request object and assign them locally
    $dDate = InputUtils::legacyFilterInputArr($_POST, 'Date');
    $sTitle = InputUtils::legacyFilterInputArr($_POST, 'Title');
    $sDescription = InputUtils::legacyFilterInputArr($_POST, 'Description');

    // Initialize the error flag
    $bErrorFlag = false;

    // Validate Date
    if (strlen($dDate) > 0) {
        list($iYear, $iMonth, $iDay) = sscanf($dDate, '%04d-%02d-%02d');
        if (!checkdate($iMonth, $iDay, $iYear)) {
            $sDateError = '<span class="text-error">' . gettext('Not a valid date') . '</span>';
            $bErrorFlag = true;
        }
    }

    // If no errors, then let's update...
    if (!$bErrorFlag) {
        // New deposit slip
        if ($iFundRaiserID <= 0) {
            $fundraiser = new FundRaiser();
            $fundraiser
                ->setDate($dDate)
                ->setTitle($sTitle)
                ->setDescription($sDescription)
                ->setEnteredBy(AuthenticationManager::getCurrentUser()->getId())
                ->setEnteredDate(DateTimeUtils::getToday()->format('YmdHis'));
            $fundraiser->save();
            $fundraiser->reload();

            $iFundRaiserID = $fundraiser->getId();
            // Existing record (update)
        } else {
            $fundraiser = FundRaiserQuery::create()->findOneById($iFundRaiserID);
            $fundraiser
                ->setDate($dDate)
                ->setTitle($sTitle)
                ->setDescription($sDescription)
                ->setEnteredBy(AuthenticationManager::getCurrentUser()->getId())
                ->setEnteredDate(DateTimeUtils::getToday()->format('YmdHis'));
            $fundraiser->save();
        }

        $_SESSION['iCurrentFundraiser'] = $iFundRaiserID;

        if (isset($_POST['FundRaiserSubmit'])) {
            // Only use linkBack if it was explicitly provided in the original request
            if ($linkBackProvided) {
                RedirectUtils::redirect($linkBack);
            } else {
                //Send to the view of this FundRaiser
                RedirectUtils::redirect('FundRaiserEditor.php?FundRaiserID=' . $iFundRaiserID);
            }
        }
    }
} else {
    //FirstPass
    //Are we editing or adding?
    if ($fundraiser) {
        //Editing....
        //Get all the data on this record
        $dDate = $fundraiser->getDate();
        $sTitle = $fundraiser->getTitle();
        $sDescription = $fundraiser->getDescription();


        // Use addAscendingOrderByColumn with raw SQL to preserve natural sort
        // (e.g., A2 before A10) matching the original ORDER BY
        $donatedItems = DonatedItemQuery::create()
            ->filterByFrId((int) $iFundRaiserID)
            ->addAscendingOrderByColumn('di_multibuy')
            ->addAscendingOrderByColumn('SUBSTR(di_item,1,1)')
            ->addAscendingOrderByColumn('cast(SUBSTR(di_item,2) as unsigned integer)')
            ->addAscendingOrderByColumn('SUBSTR(di_item,4)')
            ->find();

        // Preload all referenced person IDs to avoid N+1 queries
        $personIds = [];
        foreach ($donatedItems as $item) {
            if ($item->getDonorId()) {
                $personIds[] = (int) $item->getDonorId();
            }
            if ($item->getBuyerId()) {
                $personIds[] = (int) $item->getBuyerId();
            }
        }
        $personMap = [];
        if (!empty($personIds)) {
            $persons = PersonQuery::create()->findPks(array_unique($personIds));
            foreach ($persons as $person) {
                $personMap[$person->getId()] = $person;
            }
        }
        $_SESSION['iCurrentFundraiser'] = $iFundRaiserID;        // Probably redundant

    } else {
        $dDate = date_create('now');    // Set default date to today
        $sTitle = '';
        $sDescription = '';
        $donatedItems = null;
    }
}

$aBreadcrumbs = PageHeader::breadcrumbs([
    [gettext('Fundraiser'), '/FindFundRaiser.php'],
    [gettext('Edit Fundraiser')],
]);
require_once __DIR__ . '/Include/Header.php';

?>
<div class="card mb-3">
    <div class="card-body">
        <form method="post" action="FundRaiserEditor.php?<?= ($linkBackProvided ? 'linkBack=' . urlencode($linkBack) . '&' : '') . 'FundRaiserID=' . $iFundRaiserID ?>" name="FundRaiserEditor">

            <div class="mb-3">
                <label class="form-label" for="Date"><?= gettext('Date') ?>:</label>
                <input type="text" name="Date" value="<?= $dDate->format("Y-m-d") ?>" maxlength="10" id="Date" class="form-control date-picker" style="max-width:180px">
                <?php if ($sDateError): ?><div class="text-danger small"><?= $sDateError ?></div><?php endif; ?>
            </div>

            <div class="mb-3">
                <label class="form-label" for="Title"><?= gettext('Title') ?>:</label>
                <input type="text" class="form-control" name="Title" id="Title" value="<?= InputUtils::escapeAttribute($sTitle) ?>">
            </div>

            <div class="mb-3">
                <label class="form-label" for="Description"><?= gettext('Description') ?>:</label>
                <textarea class="form-control" name="Description" id="Description" rows="5"><?= InputUtils::escapeHTML($sDescription) ?></textarea>
            </div>

            <div class="d-flex gap-2">
                <input type="submit" class="btn btn-primary" value="<?= gettext('Save') ?>" name="FundRaiserSubmit">
                <input type="button" class="btn btn-secondary" value="<?= gettext('Cancel') ?>" name="FundRaiserCancel" onclick="javascript:document.location='FindFundRaiser.php';">
            </div>

        </form>
    </div>
</div>
<?php if ($iFundRaiserID > 0): ?>
<div class="card mb-3">
    <div class="card-body">
        <div class="d-flex flex-wrap gap-2">
        <a href="DonatedItemEditor.php?CurrentFundraiser=<?= $iFundRaiserID ?>&linkBack=FundRaiserEditor.php?FundRaiserID=<?= $iFundRaiserID ?>&CurrentFundraiser=<?= $iFundRaiserID ?>" class="btn btn-success">
            <i class="ti ti-plus me-1"></i><?= gettext('Add Donated Item') ?>
        </a>
        <div class="dropdown">
            <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" data-bs-display="static" aria-expanded="false">
                <i class="ti ti-file-text me-1"></i><?= gettext('Reports') ?>
            </button>
            <div class="dropdown-menu">
                <a class="dropdown-item" href="Reports/FRCatalog.php?CurrentFundraiser=<?= $iFundRaiserID ?>">
                    <i class="ti ti-book me-2"></i><?= gettext('Generate Catalog') ?>
                </a>
                <a class="dropdown-item" href="Reports/FRBidSheets.php?CurrentFundraiser=<?= $iFundRaiserID ?>">
                    <i class="ti ti-list me-2"></i><?= gettext('Generate Bid Sheets') ?>
                </a>
                <a class="dropdown-item" href="Reports/FRCertificates.php?CurrentFundraiser=<?= $iFundRaiserID ?>">
                    <i class="ti ti-certificate me-2"></i><?= gettext('Generate Certificates') ?>
                </a>
            </div>
        </div>
        <a href="BatchWinnerEntry.php?CurrentFundraiser=<?= $iFundRaiserID ?>&linkBack=FundRaiserEditor.php?FundRaiserID=<?= $iFundRaiserID ?>&CurrentFundraiser=<?= $iFundRaiserID ?>" class="btn btn-secondary">
            <i class="ti ti-trophy me-1"></i><?= gettext('Batch Winner Entry') ?>
        </a>
    </div>
</div>
<div class="card">
    <div class="card-header">
        <h3 class="card-title"><?= gettext('Donated items for this fundraiser') ?></h3>
    </div>
    <div class="card-body" style="overflow: visible;">
    <table class="table table-vcenter table-hover w-100">
        <thead>
        <tr>
            <th><?= gettext('Item') ?></th>
            <th><?= gettext('Multiple') ?></th>
            <th><?= gettext('Donor') ?></th>
            <th><?= gettext('Buyer') ?></th>
            <th><?= gettext('Title') ?></th>
            <th><?= gettext('Sale Price') ?></th>
            <th><?= gettext('Est. Value') ?></th>
            <th><?= gettext('Material') ?></th>
            <th><?= gettext('Minimum') ?></th>
            <th class="w-1 no-export"><?= gettext('Actions') ?></th>
        </tr>
        </thead>
        <tbody>
        <?php
        //Loop through all donated items
        if ($donatedItems !== null && $donatedItems->count() > 0) {
            foreach ($donatedItems as $item) {
                $itemName = $item->getItem() ?: '~';
                $donor = $item->getDonorId() ? ($personMap[(int) $item->getDonorId()] ?? null) : null;
                $buyer = $item->getBuyerId() ? ($personMap[(int) $item->getBuyerId()] ?? null) : null;
                $donorFirstName = $donor ? $donor->getFirstName() : '';
                $donorLastName = $donor ? $donor->getLastName() : '';
                $buyerFirstName = $buyer ? $buyer->getFirstName() : '';
                $buyerLastName = $buyer ? $buyer->getLastName() : '';

                ?>
                <tr>
                    <td><?= InputUtils::escapeHTML($itemName) ?></td>
                    <td><?= $item->getMultibuy() ? '<span class="badge bg-info">X</span>' : '' ?></td>
                    <td><?= InputUtils::escapeHTML($donorFirstName) . ' ' . InputUtils::escapeHTML($donorLastName) ?></td>
                    <td>
                        <?php if ($item->getMultibuy()) {
                            echo '<span class="text-body-secondary">' . gettext('Multiple') . '</span>';
                        } else {
                            echo InputUtils::escapeHTML($buyerFirstName) . ' ' . InputUtils::escapeHTML($buyerLastName);
                        } ?>
                    </td>
                    <td><?= InputUtils::escapeHTML($item->getTitle()) ?></td>
                    <td class="text-end"><?= InputUtils::escapeHTML($item->getSellprice()) ?></td>
                    <td class="text-end"><?= InputUtils::escapeHTML($item->getEstprice()) ?></td>
                    <td class="text-end"><?= InputUtils::escapeHTML($item->getMaterialValue()) ?></td>
                    <td class="text-end"><?= InputUtils::escapeHTML($item->getMinimum()) ?></td>
                    <td class="w-1">
                        <div class="dropdown">
                            <button class="btn btn-sm btn-ghost-secondary" type="button" data-bs-toggle="dropdown" data-bs-display="static" aria-expanded="false">
                                <i class="ti ti-dots-vertical"></i>
                            </button>
                            <div class="dropdown-menu dropdown-menu-end">
                                <a class="dropdown-item" href="DonatedItemEditor.php?DonatedItemID=<?= (int) $item->getId() ?>&linkBack=FundRaiserEditor.php?FundRaiserID=<?= (int)$iFundRaiserID ?>">
                                    <i class="ti ti-pencil me-2"></i><?= gettext('Edit') ?>
                                </a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item text-danger" href="DonatedItemDelete.php?DonatedItemID=<?= (int) $item->getId() ?>&linkBack=FundRaiserEditor.php?FundRaiserID=<?= (int)$iFundRaiserID ?>">
                                    <i class="ti ti-trash me-2"></i><?= gettext('Delete') ?>
                                </a>
                            </div>
                        </div>
                    </td>
                </tr>
                <?php
            } // foreach
        } // if
        ?>
        </tbody>
    </table>
    </div>
</div>
<?php endif; ?>
<?php
require_once __DIR__ . '/Include/Footer.php';
