<?php

include "../includes/admin_auth.php";
include "../config/database.php";

/*
|--------------------------------------------------------------------------
| Get All Schemes
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        p.*,

        (
            SELECT COUNT(*)
            FROM subscriptions s
            WHERE s.plan_id = p.id
            AND s.status = 'active'
        ) AS total_members,

        (
            SELECT COALESCE(SUM(s.hands), 0)
            FROM subscriptions s
            WHERE s.plan_id = p.id
            AND s.status = 'active'
        ) AS total_hands

    FROM plans p

    ORDER BY p.id DESC
");

$stmt->execute();

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

?>

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <title>Manage Schemes</title>

    <!-- Existing Admin Styles -->
    <link
        rel="stylesheet"
        href="../assets/css/admin.css"
    >

    <link
        rel="stylesheet"
        href="../assets/css/responsive.css"
    >

    <!-- NEW SCHEME PAGE STYLES -->
    <link
        rel="stylesheet"
        href="../assets/css/admin-plan.css"
    >

    <link
        rel="stylesheet"
        href="../assets/css/admin-plan-responsive.css"
    >

    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
    >

</head>


<body>


<?php include "../includes/admin_sidebar.php"; ?>

<div class="sidebar-overlay"></div>

<?php include "../includes/admin_topbar.php"; ?>


<div class="main-content">

    <main class="admin-scheme-page">


    <!-- =====================================================
         PAGE HEADER
    ====================================================== -->

    <section class="admin-scheme-heading">

        <div class="admin-scheme-heading-text">

            <span class="admin-scheme-heading-icon">
                <i class="fas fa-layer-group"></i>
            </span>

            <div>

                <h1>Manage Schemes</h1>

                <p>
                    View and manage all contribution and savings schemes.
                </p>

            </div>

        </div>


        <a
            href="add_plan.php"
            class="admin-scheme-create-btn"
        >

            <i class="fas fa-plus"></i>

            <span>Add New Scheme</span>

        </a>

    </section>



    <!-- =====================================================
         SCHEME COUNT
    ====================================================== -->

    <?php if (count($schemes) > 0): ?>

        <div class="admin-scheme-summary">

            <div class="admin-scheme-summary-item">

                <span class="admin-scheme-summary-icon">
                    <i class="fas fa-layer-group"></i>
                </span>

                <div>

                    <strong>
                        <?= count($schemes); ?>
                    </strong>

                    <small>
                        Total Schemes
                    </small>

                </div>

            </div>

        </div>


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

        <section class="admin-scheme-grid">


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


                <?php

                /*
                |--------------------------------------------------------------------------
                | Scheme Period
                |--------------------------------------------------------------------------
                */

                $schemePeriod = "Not specified";

                if (
                    !empty($scheme['start_month']) &&
                    !empty($scheme['start_year']) &&
                    !empty($scheme['duration'])
                ) {

                    try {

                        $startDate = new DateTime(
                            $scheme['start_year']
                            . '-'
                            . str_pad(
                                $scheme['start_month'],
                                2,
                                '0',
                                STR_PAD_LEFT
                            )
                            . '-01'
                        );

                        $endDate = clone $startDate;

                        $endDate->modify(
                            '+' . ((int)$scheme['duration'] - 1) . ' months'
                        );

                        $schemePeriod =
                            $startDate->format('F Y')
                            . ' – '
                            . $endDate->format('F Y');

                    } catch (Exception $e) {

                        $schemePeriod = "Not specified";

                    }

                }


                /*
                |--------------------------------------------------------------------------
                | Package Items
                |--------------------------------------------------------------------------
                */

                $packageItems = [];

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

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

                }


                /*
                |--------------------------------------------------------------------------
                | Image
                |--------------------------------------------------------------------------
                */

                $hasImage = !empty($scheme['plan_image']);

                $imagePath = "../assets/uploads/plans/" .
                    htmlspecialchars($scheme['plan_image']);


                /*
                |--------------------------------------------------------------------------
                | Status
                |--------------------------------------------------------------------------
                */

                $isActive = ($scheme['status'] === 'active');

                ?>


                <!-- =====================================================
                     SCHEME CARD
                ====================================================== -->

                <article class="admin-scheme-card">


                    <!-- IMAGE AREA -->

                    <div class="admin-scheme-image-area">

                        <?php if ($hasImage): ?>

                            <img
                                src="<?= $imagePath; ?>"
                                alt="<?= htmlspecialchars($scheme['plan_name']); ?>"
                                class="admin-scheme-main-image"
                            >

                        <?php else: ?>

                            <div class="admin-scheme-no-image">

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

                                <span>No Scheme Image</span>

                            </div>

                        <?php endif; ?>


                        <!-- TYPE -->

                        <span class="admin-scheme-type-badge">

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

                        </span>


                        <!-- STATUS -->

                        <span
                            class="admin-scheme-status-badge
                            <?= $isActive ? 'is-active' : 'is-inactive'; ?>"
                        >

                            <i
                                class="fas
                                <?= $isActive
                                    ? 'fa-circle-check'
                                    : 'fa-circle-xmark';
                                ?>"
                            ></i>

                            <?= $isActive ? 'Active' : 'Inactive'; ?>

                        </span>

                    </div>



                    <!-- CONTENT -->

                    <div class="admin-scheme-card-content">


                        <!-- TITLE -->

                        <div class="admin-scheme-title-block">

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

                            <p>
                                <?= htmlspecialchars(
                                    $scheme['description'] ?? 'No description available.'
                                ); ?>
                            </p>

                        </div>



                        <!-- MAIN INFORMATION -->

                        <div class="admin-scheme-info-grid">


                            <!-- AMOUNT -->

                            <div class="admin-scheme-info-box">

                                <span class="admin-scheme-info-icon">
                                    <i class="fas fa-money-bill-wave"></i>
                                </span>

                                <div>

                                    <small>Contribution</small>

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

                                    <em>
                                        Per Hand
                                    </em>

                                </div>

                            </div>



                            <!-- FREQUENCY -->

                            <div class="admin-scheme-info-box">

                                <span class="admin-scheme-info-icon">
                                    <i class="fas fa-repeat"></i>
                                </span>

                                <div>

                                    <small>Frequency</small>

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

                                </div>

                            </div>



                            <!-- DURATION -->

                            <div class="admin-scheme-info-box">

                                <span class="admin-scheme-info-icon">
                                    <i class="fas fa-hourglass-half"></i>
                                </span>

                                <div>

                                    <small>Duration</small>

                                    <strong>
                                        <?= !empty($scheme['duration'])
                                            ? (int)$scheme['duration'] . ' Months'
                                            : 'Not specified';
                                        ?>
                                    </strong>

                                </div>

                            </div>



                            <!-- PERIOD -->

                            <div class="admin-scheme-info-box">

                                <span class="admin-scheme-info-icon">
                                    <i class="fas fa-calendar-days"></i>
                                </span>

                                <div>

                                    <small>Scheme Period</small>

                                    <strong>
                                        <?= htmlspecialchars($schemePeriod); ?>
                                    </strong>

                                </div>

                            </div>



                            <!-- MEMBERS -->

                            <div class="admin-scheme-info-box">

                                <span class="admin-scheme-info-icon">
                                    <i class="fas fa-users"></i>
                                </span>

                                <div>

                                    <small>Members</small>

                                    <strong>
                                        <?= (int)$scheme['total_members']; ?>
                                    </strong>

                                </div>

                            </div>



                            <!-- HANDS -->

                            <div class="admin-scheme-info-box">

                                <span class="admin-scheme-info-icon">
                                    <i class="fas fa-layer-group"></i>
                                </span>

                                <div>

                                    <small>Total Hands</small>

                                    <strong>
                                        <?= (int)$scheme['total_hands']; ?>
                                    </strong>

                                </div>

                            </div>


                        </div>



                        <!-- PACKAGE -->

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

                            <div class="admin-scheme-package">

                                <div class="admin-scheme-section-title">

                                    <i class="fas fa-box-open"></i>

                                    <span>What Members Will Get</span>

                                </div>


                                <ul>

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

                                        <?php

                                        $item = trim($item);

                                        if ($item === '') {
                                            continue;
                                        }

                                        ?>

                                        <li>

                                            <i class="fas fa-check"></i>

                                            <span>
                                                <?= htmlspecialchars($item); ?>
                                            </span>

                                        </li>

                                    <?php endforeach; ?>

                                </ul>

                            </div>

                        <?php endif; ?>



                        <!-- CREATED DATE -->

                        <div class="admin-scheme-created">

                            <i class="fas fa-clock"></i>

                            Created:

                            <?= !empty($scheme['created_at'])
                                ? date(
                                    'd M Y',
                                    strtotime($scheme['created_at'])
                                )
                                : 'Not available';
                            ?>

                        </div>



                    </div>



                    <!-- ACTIONS -->

                    <div class="admin-scheme-actions">


                        <a
                            href="scheme_members.php?plan=<?= (int)$scheme['id']; ?>"
                            class="admin-scheme-action members-action"
                            title="View Members"
                        >

                            <i class="fas fa-users"></i>

                            <span>Members</span>

                        </a>


                        <a
                            href="edit_plan.php?id=<?= (int)$scheme['id']; ?>"
                            class="admin-scheme-action edit-action"
                            title="Edit Scheme"
                        >

                            <i class="fas fa-pen"></i>

                            <span>Edit</span>

                        </a>


                        <?php if ($isActive): ?>

                            <a
                                href="toggle_plan.php?id=<?= (int)$scheme['id']; ?>"
                                class="admin-scheme-action pause-action"
                                title="Deactivate Scheme"
                            >

                                <i class="fas fa-pause"></i>

                                <span>Deactivate</span>

                            </a>

                        <?php else: ?>

                            <a
                                href="toggle_plan.php?id=<?= (int)$scheme['id']; ?>"
                                class="admin-scheme-action activate-action"
                                title="Activate Scheme"
                            >

                                <i class="fas fa-play"></i>

                                <span>Activate</span>

                            </a>

                        <?php endif; ?>


                    </div>


                </article>


            <?php endforeach; ?>


        </section>


    <?php else: ?>


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

        <section class="admin-scheme-empty">

            <div class="admin-scheme-empty-icon">

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

            </div>

            <h2>No Schemes Created Yet</h2>

            <p>
                You have not created any contribution schemes.
                Create your first scheme to get started.
            </p>

            <a
                href="add_plan.php"
                class="admin-scheme-create-btn"
            >

                <i class="fas fa-plus"></i>

                Create First Scheme

            </a>

        </section>


    <?php endif; ?>


</main>

</div>


<script src="../assets/js/admin.js"></script>

</body>

</html>