<?php

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

use ChurchCRM\Authentication\AuthenticationManager;
use ChurchCRM\dto\SystemURLs;
use ChurchCRM\model\ChurchCRM\DonatedItem;
use ChurchCRM\model\ChurchCRM\DonatedItemQuery;
use ChurchCRM\model\ChurchCRM\FundRaiserQuery;
use ChurchCRM\Utils\InputUtils;
use ChurchCRM\Utils\MiscUtils;
use ChurchCRM\Utils\RedirectUtils;
use ChurchCRM\view\PageHeader;

$iDonatedItemID = InputUtils::filterInt(InputUtils::legacyFilterInputArr($_GET, 'DonatedItemID', 'int'));
$linkBack = RedirectUtils::getLinkBackFromRequest('v2/dashboard');
$iCurrentFundraiser = InputUtils::filterInt(InputUtils::legacyFilterInputArr($_GET, 'CurrentFundraiser'));

if ($iDonatedItemID > 0) {
    $existingItem = DonatedItemQuery::create()->findPk((int) $iDonatedItemID);
    $iCurrentFundraiser = $existingItem?->getFrId();
}

if ($iCurrentFundraiser) {
    $fundraiser = FundRaiserQuery::create()->findPk((int) $iCurrentFundraiser);
    $_SESSION['iCurrentFundraiser'] = $iCurrentFundraiser;
} else {
    $iCurrentFundraiser = $_SESSION['iCurrentFundraiser'];
}

$sPageTitle = gettext('Donated Item Editor');
$sPageSubtitle = gettext('Add or edit items donated for fundraising events');

// Is this the second pass?
if (isset($_POST['DonatedItemSubmit']) || isset($_POST['DonatedItemSubmitAndAdd'])) {
    //Get all the variables from the request object and assign them locally
    $sItem = InputUtils::legacyFilterInputArr($_POST, 'Item');
    $bMultibuy = InputUtils::legacyFilterInputArr($_POST, 'Multibuy', 'int');
    $iDonor = InputUtils::legacyFilterInputArr($_POST, 'Donor', 'int');
    $iBuyer = InputUtils::legacyFilterInputArr($_POST, 'Buyer', 'int');
    $sTitle = InputUtils::legacyFilterInputArr($_POST, 'Title');
    $sDescription = InputUtils::legacyFilterInputArr($_POST, 'Description');
    $nSellPrice = InputUtils::legacyFilterInputArr($_POST, 'SellPrice');
    $nEstPrice = InputUtils::legacyFilterInputArr($_POST, 'EstPrice');
    $nMaterialValue = InputUtils::legacyFilterInputArr($_POST, 'MaterialValue');
    $nMinimumPrice = InputUtils::legacyFilterInputArr($_POST, 'MinimumPrice');
    $sPictureURL = InputUtils::legacyFilterInputArr($_POST, 'PictureURL');

    if (!$bMultibuy) {
        $bMultibuy = 0;
    }
    if (!$iBuyer) {
        $iBuyer = 0;
    }
    // New DonatedItem or deposit
    if ($iDonatedItemID < 1) {
        $donatedItem = new DonatedItem();
        $donatedItem
            ->setFrId($iCurrentFundraiser)
            ->setItem($sItem)
            ->setMultibuy($bMultibuy)
            ->setDonorId($iDonor)
            ->setBuyerId($iBuyer)
            ->setTitle(html_entity_decode($sTitle))
            ->setDescription(html_entity_decode($sDescription))
            ->setSellprice($nSellPrice)
            ->setEstprice($nEstPrice)
            ->setMaterialValue($nMaterialValue)
            ->setMinimum($nMinimumPrice)
            ->setPicture($sPictureURL)
            ->setEnteredby(AuthenticationManager::getCurrentUser()->getId())
            ->setEntereddate(date('YmdHis'));
        $donatedItem->save();

        $bGetKeyBack = true;
        // Existing record (update)
    } else {
        $donatedItem = DonatedItemQuery::create()->findOneById($iDonatedItemID);
        $donatedItem
            ->setFrId($iCurrentFundraiser)
            ->setItem($sItem)
            ->setMultibuy($bMultibuy)
            ->setDonorId($iDonor)
            ->setBuyerId($iBuyer)
            ->setTitle(html_entity_decode($sTitle))
            ->setDescription(html_entity_decode($sDescription))
            ->setSellprice($nSellPrice)
            ->setEstprice($nEstPrice)
            ->setMaterialValue($nMaterialValue)
            ->setMinimum($nMinimumPrice)
            ->setPicture($sPictureURL)
            ->setEnteredby(AuthenticationManager::getCurrentUser()->getId())
            ->setEntereddate(date('YmdHis'));
        $donatedItem->save();
        $bGetKeyBack = false;
    }

    // If this is a new DonatedItem, get the key back from the saved object
    if ($bGetKeyBack) {
        $iDonatedItemID = $donatedItem->getId();
    }

    if (isset($_POST['DonatedItemSubmit'])) {
        // Check for redirection to another page after saving information: (ie. DonatedItemEditor.php?previousPage=prev.php?a=1;b=2;c=3)
        if ($linkBack !== '') {
            RedirectUtils::redirect($linkBack);
        } else {
            //Send to the view of this DonatedItem
            RedirectUtils::redirect('DonatedItemEditor.php?DonatedItemID=' . $iDonatedItemID . '&linkBack=' . $linkBack);
        }
    } elseif (isset($_POST['DonatedItemSubmitAndAdd'])) {
        //Reload to editor to add another record
        RedirectUtils::redirect("DonatedItemEditor.php?CurrentFundraiser=$iCurrentFundraiser&linkBack=" . $linkBack);
    }
} else {
    //FirstPass
    //Are we editing or adding?
    if ($iDonatedItemID > 0) {
        //Editing....
        //Get all the data on this record
        $donatedItemRecord = DonatedItemQuery::create()->findPk((int) $iDonatedItemID);
        if ($donatedItemRecord === null) {
            RedirectUtils::redirect($linkBack);
        }

        $sItem = $donatedItemRecord->getItem();
        $bMultibuy = $donatedItemRecord->getMultibuy();
        $iDonor = $donatedItemRecord->getDonorId();
        $iBuyer = $donatedItemRecord->getBuyerId();
        $sTitle = $donatedItemRecord->getTitle();
        $sDescription = $donatedItemRecord->getDescription();
        $nSellPrice = $donatedItemRecord->getSellprice();
        $nEstPrice = $donatedItemRecord->getEstprice();
        $nMaterialValue = $donatedItemRecord->getMaterialValue();
        $nMinimumPrice = $donatedItemRecord->getMinimum();
        $sPictureURL = $donatedItemRecord->getPicture();
    } else {
        //Adding....
        //Set defaults
        $sItem = '';
        $bMultibuy = 0;
        $iDonor = 0;
        $iBuyer = 0;
        $sTitle = '';
        $sDescription = '';
        $nSellPrice = 0.0;
        $nEstPrice = 0.0;
        $nMaterialValue = 0.0;
        $nMinimumPrice = 0.0;
        $sPictureURL = '';
    }
}

//Get People for the drop-down
$sPeopleSQL = 'SELECT per_ID, per_FirstName, per_LastName, fam_Address1, fam_City, fam_State FROM person_per JOIN family_fam on per_fam_id=fam_id ORDER BY per_LastName, per_FirstName';

//Get Paddles for the drop-down
$sPaddleSQL = 'SELECT pn_ID, pn_Num, pn_per_ID,
                      a.per_FirstName AS buyerFirstName,
                      a.per_LastName AS buyerLastName
                      FROM paddlenum_pn
                      LEFT JOIN person_per a on a.per_ID=pn_per_ID
                      WHERE pn_fr_ID=' . $iCurrentFundraiser . ' ORDER BY pn_Num';

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

<form method="post" action="DonatedItemEditor.php?<?= 'CurrentFundraiser=' . $iCurrentFundraiser . '&DonatedItemID=' . $iDonatedItemID . '&linkBack=' . $linkBack; ?>" name="DonatedItemEditor">
    <div class="card">
        <div class="card-body">
            <div class="mb-3">
                <div class="row">
                    <div class="col-md-4 col-6">
                        <div class="mb-3">
                            <label><?= gettext('Item') ?>:</label>
                            <input type="text" name="Item" id="Item" value="<?= $sItem ?>" class="form-control">
                        </div>

                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" name="Multibuy" value="1" id="Multibuy" <?= $bMultibuy ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="Multibuy">
                                <?= gettext('Sell to everyone'); ?> (<?= gettext('Multiple items'); ?>)
                            </label>
                        </div>

                        <div class="mb-3">
                            <label><?= gettext('Donor'); ?>:</label>
                            <select name="Donor" id="Donor" class="form-select">
                                <option value="0" selected><?= gettext('Unassigned') ?></option>
                                <?php
                                $rsPeople = RunQuery($sPeopleSQL);
                                while ($aRow = mysqli_fetch_array($rsPeople)) {
                                    extract($aRow);
                                    echo '<option value="' . (int)$per_ID . '"';
                                    if ($iDonor == $per_ID) {
                                        echo ' selected';
                                    }
                                    echo '>' . InputUtils::escapeHTML($per_LastName) . ', ' . InputUtils::escapeHTML($per_FirstName);
                                    echo ' ' . InputUtils::escapeHTML(MiscUtils::formatAddressLine($fam_Address1, $fam_City, $fam_State));
                                }
                                ?>
                            </select>
                        </div>
                        <script nonce="<?= SystemURLs::getCSPNonce() ?>">
                            $(document).ready(function() {
                                var donorEl = document.getElementById("Donor");
                                if (donorEl && !donorEl.tomselect) new TomSelect(donorEl);
                            });
                        </script>

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

                        <div class="mb-3">
                            <label><?= gettext('Estimated Price') ?>:</label>
                            <input type="text" name="EstPrice" id="EstPrice" value="<?= $nEstPrice ?>" class="form-control">
                        </div>

                        <div class="mb-3">
                            <label><?= gettext('Material Value') ?>:</label>
                            <input type="text" name="MaterialValue" id="MaterialValue" value="<?= $nMaterialValue ?>" class="form-control">
                        </div>

                        <div class="mb-3">
                            <label><?= gettext('Minimum Price') ?>:</label>
                            <input type="text" name="MinimumPrice" id="MinimumPrice" value="<?= $nMinimumPrice ?>" class="form-control">
                        </div>

                    </div>

                    <div class="col-md-4 col-6">
                        <div class="mb-3">
                            <label><?= gettext('Buyer') ?>:</label>
                            <?php if ($bMultibuy) {
                                echo gettext('Multiple');
                            } else {
                                ?>
                                <select name="Buyer" class="form-select">
                                    <option value="0" selected><?= gettext('Unassigned') ?></option>
                                <?php
                                $rsBuyers = RunQuery($sPaddleSQL);
                                while ($aRow = mysqli_fetch_array($rsBuyers)) {
                                    extract($aRow);
                                    echo '<option value="' . (int)$pn_per_ID . '"';
                                    if ($iBuyer == $pn_per_ID) {
                                        echo ' selected';
                                    }
                                    echo '>' . (int)$pn_Num . ': ' . InputUtils::escapeHTML($buyerFirstName) . ' ' . InputUtils::escapeHTML($buyerLastName);
                                }
                            }
                            ?>

                                </select>
                        </div>

                        <div class="mb-3">
                            <label><?= gettext('Final Price') ?>:</label>
                            <input type="text" name="SellPrice" id="SellPrice" value="<?= $nSellPrice ?>" class="form-control">
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= gettext('Replicate item') ?></label>
                            <div class="input-group">
                                <input type="text" name="NumberCopies" id="NumberCopies" value="0" class="form-control">
                                <input type="button" class="btn btn-primary" value="<?= gettext('Go') ?>" name="DonatedItemReplicate" onclick="javascript:document.location = 'DonatedItemReplicate.php?DonatedItemID=<?= $iDonatedItemID ?>&Count=' + NumberCopies.value">
                            </div>
                        </div>

                    </div>

                    <div class="col-md-6 col-12">
                        <div class="mb-3">
                            <label><?= gettext('Description') ?>:</label>
                            <textarea name="Description" rows="5" cols="90" class="form-control"><?= InputUtils::escapeAttribute($sDescription) ?></textarea>
                        </div>

                        <div class="mb-3">
                            <label><?= gettext('Picture URL') ?>:</label>
                            <textarea name="PictureURL" rows="1" cols="90" class="form-control"><?= InputUtils::escapeAttribute($sPictureURL) ?></textarea>
                        </div>

                        <?php if ($sPictureURL !== '') : ?>
                            <div class="mb-3"><img src="<?= InputUtils::escapeAttribute($sPictureURL) ?>" /></div>
                        <?php endif; ?>

                    </div>

                </div> <!-- row -->
            </div>

            <div class="mb-3 text-center">
                <input type="submit" class="btn btn-primary" value="<?= gettext('Save') ?>" name="DonatedItemSubmit">
                <?php if (AuthenticationManager::getCurrentUser()->isAddRecordsEnabled()) : ?>
                    <input type="submit" class="btn btn-primary" value="<?= gettext('Save and Add'); ?>" name="DonatedItemSubmitAndAdd">
                <?php endif; ?>
                <input type="button" class="btn btn-secondary" value="<?= gettext('Cancel') ?>" name="DonatedItemCancel" onclick="document.location = '<?= RedirectUtils::escapeRedirectUrl($linkBack, 'v2/dashboard'); ?>';">
            </div>

        </div>
    </div>
</form>
<?php
require_once __DIR__ . '/Include/Footer.php';
