<?php

/* =========================================================
   COMPLETE BLISS - ALL PUBLIC SCHEMES
========================================================= */

require_once __DIR__ . '/config/database.php';


/* =========================================================
   FILTER VALUES
========================================================= */

$search =
    trim(
        $_GET['search'] ?? ''
    );


$planType =
    trim(
        $_GET['type'] ?? ''
    );


$frequency =
    trim(
        $_GET['frequency'] ?? ''
    );


$schemePage =
    isset($_GET['page'])
        ? max(1, (int) $_GET['page'])
        : 1;


$schemesPerPage = 9;


/* =========================================================
   VALID FILTER VALUES
========================================================= */

$allowedTypes = [
    'Savings',
    'Food',
    'Contribution'
];


$allowedFrequencies = [
    'Daily',
    'Weekly',
    'Monthly',
    'Yearly'
];


if (
    $planType !== '' &&
    !in_array(
        $planType,
        $allowedTypes,
        true
    )
) {

    $planType = '';

}


if (
    $frequency !== '' &&
    !in_array(
        $frequency,
        $allowedFrequencies,
        true
    )
) {

    $frequency = '';

}


/* =========================================================
   BUILD DATABASE CONDITIONS
========================================================= */

$where = [
    "status = 'active'"
];


$params = [];


/* SEARCH */

if ($search !== '') {

    $where[] = "
        (
            plan_name LIKE :search
            OR description LIKE :search
            OR package_items LIKE :search
        )
    ";


    $params['search'] =
        '%' . $search . '%';

}


/* TYPE */

if ($planType !== '') {

    $where[] =
        "plan_type = :plan_type";


    $params['plan_type'] =
        $planType;

}


/* FREQUENCY */

if ($frequency !== '') {

    $where[] =
        "frequency = :frequency";


    $params['frequency'] =
        $frequency;

}


$whereSql =
    implode(
        ' AND ',
        $where
    );


/* =========================================================
   COUNT RESULTS
========================================================= */

$countSql = "

    SELECT COUNT(*)

    FROM plans

    WHERE {$whereSql}

";


$countStatement =
    $pdo->prepare(
        $countSql
    );


$countStatement->execute(
    $params
);


$totalSchemes =
    (int)
    $countStatement->fetchColumn();


$totalPages =
    $totalSchemes > 0
        ? (int) ceil(
            $totalSchemes /
            $schemesPerPage
        )
        : 1;


if (
    $schemePage >
    $totalPages
) {

    $schemePage =
        $totalPages;

}


$offset =
    ($schemePage - 1)
    * $schemesPerPage;


/* =========================================================
   FETCH SCHEMES
========================================================= */

$schemeSql = "

    SELECT

        id,
        plan_name,
        plan_type,
        amount,
        frequency,
        duration,
        description,
        plan_image,
        package_items,
        start_month,
        start_year

    FROM plans

    WHERE {$whereSql}

    ORDER BY created_at DESC

    LIMIT {$schemesPerPage}
    OFFSET {$offset}

";


$schemeStatement =
    $pdo->prepare(
        $schemeSql
    );


$schemeStatement->execute(
    $params
);


$schemes =
    $schemeStatement->fetchAll(
        PDO::FETCH_ASSOC
    );


/* =========================================================
   HEADER
========================================================= */
$pageTitle =
    'Contribution Schemes | Complete Bliss Solutions';

$pageDescription =
    'Explore available Complete Bliss contribution schemes for food, household needs, savings goals and other planned expenses.';

$pageKeywords =
    'Complete Bliss schemes, contribution plans Nigeria, savings schemes, food schemes, household contribution plans';

    
require_once
    __DIR__ .
    '/public-site/includes/header.php';


require_once
    __DIR__ .
    '/public-site/includes/navbar.php';

?>


<main>


    <!-- =====================================================
         HERO
    ====================================================== -->

    <section class="cbx-all-schemes-hero">

        <div class="cbx-container">


            <div class="cbx-all-schemes-hero-content">


                <a
                    href="index.php#schemes"
                    class="cbx-all-schemes-back"
                >

                    <i class="fa-solid fa-arrow-left"></i>

                    Back to Home

                </a>


                <div class="cbx-all-schemes-tag">

                    <i class="fa-solid fa-layer-group"></i>

                    AVAILABLE SCHEMES

                </div>


                <h1>

                    Find a plan that

                    <span>
                        fits your goal.
                    </span>

                </h1>


                <p>
                    Explore all currently available Complete Bliss
                    schemes, compare contribution amounts and
                    choose something worth working towards.
                </p>


                <div class="cbx-all-schemes-stats">


                    <div>

                        <strong>
                            <?= number_format(
                                $totalSchemes
                            ) ?>
                        </strong>

                        <span>
                            Available Schemes
                        </span>

                    </div>


                    <div>

                        <strong>
                            <?= number_format(
                                $schemePage
                            ) ?>
                        </strong>

                        <span>
                            Current Page
                        </span>

                    </div>


                    <div>

                        <strong>
                            <?= number_format(
                                $totalPages
                            ) ?>
                        </strong>

                        <span>
                            Total Pages
                        </span>

                    </div>


                </div>


            </div>


        </div>

    </section>



    <!-- =====================================================
         SCHEMES
    ====================================================== -->

    <section class="cbx-all-schemes-body">

        <div class="cbx-container">


            <!-- =================================================
                 FILTER
            ================================================== -->

            <form
                method="GET"
                action="schemes.php"
                class="cbx-scheme-filter"
            >


                <!-- SEARCH -->

                <div class="cbx-scheme-search">


                    <i class="fa-solid fa-magnifying-glass"></i>


                    <input
                        type="search"
                        name="search"
                        placeholder="Search schemes..."
                        value="<?= htmlspecialchars($search) ?>"
                    >


                </div>



                <!-- TYPE -->

                <div class="cbx-scheme-select">


                    <i class="fa-solid fa-box"></i>


                    <select name="type">

                        <option value="">
                            All Scheme Types
                        </option>


                        <?php foreach ($allowedTypes as $type): ?>

                            <option
                                value="<?= htmlspecialchars($type) ?>"
                                <?= $planType === $type
                                    ? 'selected'
                                    : '' ?>
                            >

                                <?= htmlspecialchars($type) ?>

                            </option>

                        <?php endforeach; ?>


                    </select>


                </div>



                <!-- FREQUENCY -->

                <div class="cbx-scheme-select">


                    <i class="fa-solid fa-calendar-days"></i>


                    <select name="frequency">

                        <option value="">
                            All Frequencies
                        </option>


                        <?php foreach ($allowedFrequencies as $item): ?>

                            <option
                                value="<?= htmlspecialchars($item) ?>"
                                <?= $frequency === $item
                                    ? 'selected'
                                    : '' ?>
                            >

                                <?= htmlspecialchars($item) ?>

                            </option>

                        <?php endforeach; ?>


                    </select>


                </div>



                <!-- BUTTON -->

                <button
                    type="submit"
                    class="cbx-scheme-filter-btn"
                >

                    <i class="fa-solid fa-sliders"></i>

                    Apply Filter

                </button>



                <?php if (
                    $search !== '' ||
                    $planType !== '' ||
                    $frequency !== ''
                ): ?>


                    <a
                        href="schemes.php"
                        class="cbx-scheme-filter-reset"
                    >

                        <i class="fa-solid fa-xmark"></i>

                        Clear

                    </a>


                <?php endif; ?>


            </form>



            <!-- =================================================
                 RESULT BAR
            ================================================== -->

            <div class="cbx-scheme-result-bar">


                <div>


                    <?php if ($totalSchemes > 0): ?>


                        <span>
                            Showing
                        </span>


                        <strong>

                            <?= number_format(
                                $offset + 1
                            ) ?>

                            –

                            <?= number_format(
                                min(
                                    $offset
                                    + $schemesPerPage,
                                    $totalSchemes
                                )
                            ) ?>

                        </strong>


                        <span>
                            of
                        </span>


                        <strong>
                            <?= number_format(
                                $totalSchemes
                            ) ?>
                        </strong>


                        <span>
                            schemes
                        </span>


                    <?php else: ?>


                        <span>
                            No schemes matched your search.
                        </span>


                    <?php endif; ?>


                </div>


                <div>

                    <i class="fa-solid fa-circle-check"></i>

                    Active schemes only

                </div>


            </div>



            <?php if (!empty($schemes)): ?>


                <!-- =================================================
                     GRID
                ================================================== -->

                <div class="cbx-all-scheme-grid">


                    <?php foreach ($schemes as $scheme): ?>


                        <?php

                        $schemeImage = '';

                        if (
                            !empty(
                                $scheme['plan_image']
                            )
                        ) {

                            $schemeImage =
                                'assets/uploads/plans/' .
                                rawurlencode(
                                    $scheme['plan_image']
                                );

                        }


                        $packageItems = [];

                        if (
                            !empty(
                                $scheme['package_items']
                            )
                        ) {

                            $packageItems =
                                preg_split(
                                    '/\r\n|\r|\n/',
                                    trim(
                                        $scheme['package_items']
                                    )
                                );


                            $packageItems =
                                array_values(
                                    array_filter(
                                        array_map(
                                            'trim',
                                            $packageItems
                                        )
                                    )
                                );

                        }


                        $previewItems =
                            array_slice(
                                $packageItems,
                                0,
                                3
                            );


                        $description =
                            trim(
                                $scheme['description']
                                ?? ''
                            );


                        if (
                            function_exists(
                                'mb_strimwidth'
                            )
                        ) {

                            $shortDescription =
                                mb_strimwidth(
                                    $description,
                                    0,
                                    150,
                                    '...'
                                );

                        } else {

                            $shortDescription =
                                strlen($description) > 150
                                    ? substr(
                                        $description,
                                        0,
                                        147
                                    ) . '...'
                                    : $description;

                        }

                        ?>


                        <article class="cbx-all-scheme-card">


                            <!-- IMAGE -->

                            <div class="cbx-all-scheme-image">


                                <?php if ($schemeImage !== ''): ?>


                                    <img
                                        src="<?= htmlspecialchars($schemeImage) ?>"
                                        alt="<?= htmlspecialchars($scheme['plan_name']) ?>"
                                        loading="lazy"
                                    >


                                <?php else: ?>


                                    <div class="cbx-all-scheme-placeholder">

                                        <i class="fa-solid fa-image"></i>

                                    </div>


                                <?php endif; ?>



                                <div class="cbx-all-scheme-image-overlay"></div>



                                <div class="cbx-all-scheme-badges">


                                    <span>

                                        <?= htmlspecialchars(
                                            $scheme['plan_type']
                                        ) ?>

                                    </span>


                                    <span>

                                        <i class="fa-regular fa-calendar"></i>

                                        <?= htmlspecialchars(
                                            $scheme['frequency']
                                        ) ?>

                                    </span>


                                </div>


                            </div>



                            <!-- CONTENT -->

                            <div class="cbx-all-scheme-content">


                                <div class="cbx-all-scheme-title-row">


                                    <div>

                                        <span>
                                            COMPLETE BLISS SCHEME
                                        </span>


                                        <h2>

                                            <?= htmlspecialchars(
                                                $scheme['plan_name']
                                            ) ?>

                                        </h2>

                                    </div>


                                </div>



                                <?php if ($shortDescription !== ''): ?>


                                    <p class="cbx-all-scheme-description">

                                        <?= htmlspecialchars(
                                            $shortDescription
                                        ) ?>

                                    </p>


                                <?php endif; ?>



                                <!-- DETAILS -->

                                <div class="cbx-all-scheme-details">


                                    <div>


                                        <span>
                                            Contribution
                                        </span>


                                        <strong>

                                            ₦<?= number_format(
                                                (float)
                                                $scheme['amount'],
                                                2
                                            ) ?>

                                        </strong>


                                        <small>
                                            per hand
                                        </small>


                                    </div>



                                    <div>


                                        <span>
                                            Duration
                                        </span>


                                        <strong>

                                            <?= number_format(
                                                (int)
                                                $scheme['duration']
                                            ) ?>

                                        </strong>


                                        <small>
                                            months
                                        </small>


                                    </div>


                                </div>



                                <!-- PACKAGE -->

                                <?php if (!empty($previewItems)): ?>


                                    <div class="cbx-all-scheme-package">


                                        <span class="cbx-all-scheme-package-title">

                                            <i class="fa-solid fa-gift"></i>

                                            What you can expect

                                        </span>


                                        <ul>


                                            <?php foreach ($previewItems as $item): ?>


                                                <li>

                                                    <i class="fa-solid fa-circle-check"></i>

                                                    <span>

                                                        <?= htmlspecialchars(
                                                            $item
                                                        ) ?>

                                                    </span>

                                                </li>


                                            <?php endforeach; ?>


                                        </ul>


                                        <?php if (
                                            count($packageItems) > 3
                                        ): ?>


                                            <small>

                                                +<?= count($packageItems) - 3 ?>
                                                more item<?= count($packageItems) - 3 === 1
                                                    ? ''
                                                    : 's' ?>

                                            </small>


                                        <?php endif; ?>


                                    </div>


                                <?php endif; ?>



                                <!-- BUTTON -->

                                <div class="cbx-all-scheme-actions">


                                 <a
    href="scheme.php?id=<?= (int) $scheme['id'] ?>"
    class="cbx-all-scheme-primary"
>

    View Scheme Details

    <i class="fa-solid fa-arrow-right"></i>

</a>


                                </div>


                            </div>


                        </article>


                    <?php endforeach; ?>


                </div>



                <!-- =================================================
                     PAGINATION
                ================================================== -->

                <?php if ($totalPages > 1): ?>


                    <?php

                    $queryValues = [];


                    if ($search !== '') {

                        $queryValues['search'] =
                            $search;

                    }


                    if ($planType !== '') {

                        $queryValues['type'] =
                            $planType;

                    }


                    if ($frequency !== '') {

                        $queryValues['frequency'] =
                            $frequency;

                    }


                    function schemePageUrl(
                        int $page,
                        array $queryValues
                    ): string {

                        $queryValues['page'] =
                            $page;


                        return
                            'schemes.php?' .
                            http_build_query(
                                $queryValues
                            );

                    }

                    ?>


                    <nav
                        class="cbx-scheme-pagination"
                        aria-label="Scheme pagination"
                    >


                        <!-- PREVIOUS -->

                        <?php if ($schemePage > 1): ?>


                            <a
                                href="<?= htmlspecialchars(
                                    schemePageUrl(
                                        $schemePage - 1,
                                        $queryValues
                                    )
                                ) ?>"
                                class="cbx-scheme-page-nav"
                            >

                                <i class="fa-solid fa-arrow-left"></i>

                                Previous

                            </a>


                        <?php else: ?>


                            <span
                                class="cbx-scheme-page-nav disabled"
                            >

                                <i class="fa-solid fa-arrow-left"></i>

                                Previous

                            </span>


                        <?php endif; ?>



                        <!-- NUMBERS -->

                        <div class="cbx-scheme-page-numbers">


                            <?php

                            $startPage =
                                max(
                                    1,
                                    $schemePage - 2
                                );


                            $endPage =
                                min(
                                    $totalPages,
                                    $schemePage + 2
                                );

                            ?>


                            <?php if ($startPage > 1): ?>


                                <a
                                    href="<?= htmlspecialchars(
                                        schemePageUrl(
                                            1,
                                            $queryValues
                                        )
                                    ) ?>"
                                >
                                    1
                                </a>


                                <?php if ($startPage > 2): ?>

                                    <span>
                                        ...
                                    </span>

                                <?php endif; ?>


                            <?php endif; ?>



                            <?php
                            for (
                                $pageNumber = $startPage;
                                $pageNumber <= $endPage;
                                $pageNumber++
                            ):
                            ?>


                                <a
                                    href="<?= htmlspecialchars(
                                        schemePageUrl(
                                            $pageNumber,
                                            $queryValues
                                        )
                                    ) ?>"
                                    class="<?= $pageNumber === $schemePage
                                        ? 'active'
                                        : '' ?>"
                                >

                                    <?= $pageNumber ?>

                                </a>


                            <?php endfor; ?>



                            <?php if ($endPage < $totalPages): ?>


                                <?php if (
                                    $endPage <
                                    $totalPages - 1
                                ): ?>

                                    <span>
                                        ...
                                    </span>

                                <?php endif; ?>


                                <a
                                    href="<?= htmlspecialchars(
                                        schemePageUrl(
                                            $totalPages,
                                            $queryValues
                                        )
                                    ) ?>"
                                >

                                    <?= $totalPages ?>

                                </a>


                            <?php endif; ?>


                        </div>



                        <!-- NEXT -->

                        <?php if ($schemePage < $totalPages): ?>


                            <a
                                href="<?= htmlspecialchars(
                                    schemePageUrl(
                                        $schemePage + 1,
                                        $queryValues
                                    )
                                ) ?>"
                                class="cbx-scheme-page-nav"
                            >

                                Next

                                <i class="fa-solid fa-arrow-right"></i>

                            </a>


                        <?php else: ?>


                            <span
                                class="cbx-scheme-page-nav disabled"
                            >

                                Next

                                <i class="fa-solid fa-arrow-right"></i>

                            </span>


                        <?php endif; ?>


                    </nav>


                <?php endif; ?>



            <?php else: ?>


                <!-- =================================================
                     EMPTY
                ================================================== -->

                <div class="cbx-all-schemes-empty">


                    <div>

                        <i class="fa-solid fa-magnifying-glass"></i>

                    </div>


                    <h2>
                        No Schemes Found
                    </h2>


                    <p>
                        We couldn't find an active scheme matching
                        your current search or filters.
                    </p>


                    <a href="schemes.php">

                        View All Schemes

                    </a>


                </div>


            <?php endif; ?>


        </div>

    </section>


</main>


<?php

require_once
    __DIR__ .
    '/public-site/includes/footer.php';

?>