<?php

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


/*
|--------------------------------------------------------------------------
| CSRF Protection
|--------------------------------------------------------------------------
*/

if (
    empty($_SESSION['password_reset_csrf'])
) {

    $_SESSION['password_reset_csrf'] =
        bin2hex(random_bytes(32));

}


/*
|--------------------------------------------------------------------------
| Expire Old Approved Codes
|--------------------------------------------------------------------------
*/

$pdo->query("
    UPDATE password_reset_requests

    SET status = 'expired'

    WHERE
        status = 'approved'
        AND token_expires_at IS NOT NULL
        AND token_expires_at < NOW()
");


/*
|--------------------------------------------------------------------------
| Handle Admin Actions
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $csrfToken =
        $_POST['csrf_token'] ?? '';

    $requestId =
        (int)($_POST['request_id'] ?? 0);

    $action =
        trim($_POST['action'] ?? '');


    /*
    |--------------------------------------------------------------------------
    | Validate CSRF
    |--------------------------------------------------------------------------
    */

    if (
        !hash_equals(
            $_SESSION['password_reset_csrf'],
            $csrfToken
        )
    ) {

        $_SESSION['error'] =
            "Invalid request. Please try again.";

        header(
            "Location: password-reset-requests.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Get Reset Request
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT
            prr.*,
            u.fullname,
            u.phone AS user_phone
        FROM password_reset_requests prr

        INNER JOIN users u
            ON u.id = prr.user_id

        WHERE prr.id = ?

        LIMIT 1
    ");

    $stmt->execute([$requestId]);

    $resetRequest =
        $stmt->fetch(PDO::FETCH_ASSOC);


    if (!$resetRequest) {

        $_SESSION['error'] =
            "Password reset request not found.";

        header(
            "Location: password-reset-requests.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Approve Request
    |--------------------------------------------------------------------------
    */

    if ($action === 'approve') {

        if (
            $resetRequest['status'] !== 'pending'
        ) {

            $_SESSION['error'] =
                "Only pending requests can be approved.";

            header(
                "Location: password-reset-requests.php"
            );

            exit();

        }


        /*
        |--------------------------------------------------------------------------
        | Generate One-Time Reset Code
        |--------------------------------------------------------------------------
        |
        | Example:
        | CB-482913
        |
        | Plain code is shown to admin once.
        | Only the hash is stored in database.
        |
        */

        $numericCode =
            (string) random_int(
                100000,
                999999
            );

        $resetCode =
            'CB-' . $numericCode;


        $tokenHash =
            password_hash(
                $resetCode,
                PASSWORD_DEFAULT
            );


        /*
        |--------------------------------------------------------------------------
        | Code Valid For 30 Minutes
        |--------------------------------------------------------------------------
        */

        $stmt = $pdo->prepare("
            UPDATE password_reset_requests

            SET
                token_hash = ?,
                token_expires_at =
                    DATE_ADD(
                        NOW(),
                        INTERVAL 30 MINUTE
                    ),
                status = 'approved',
                approved_at = NOW()

            WHERE id = ?
        ");


        $stmt->execute([

            $tokenHash,

            $requestId

        ]);


        /*
        |--------------------------------------------------------------------------
        | Store Code Temporarily For SweetAlert
        |--------------------------------------------------------------------------
        */

        $_SESSION['reset_code_created'] = [

            'code' =>
                $resetCode,

            'member' =>
                $resetRequest['fullname'],

            'phone' =>
                $resetRequest['phone']

        ];


        header(
            "Location: password-reset-requests.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Reject Request
    |--------------------------------------------------------------------------
    */

    if ($action === 'reject') {

        if (
            !in_array(
                $resetRequest['status'],
                [
                    'pending',
                    'approved'
                ],
                true
            )
        ) {

            $_SESSION['error'] =
                "This request can no longer be rejected.";

            header(
                "Location: password-reset-requests.php"
            );

            exit();

        }


        $stmt = $pdo->prepare("
            UPDATE password_reset_requests

            SET
                status = 'rejected',
                token_hash = NULL,
                token_expires_at = NULL

            WHERE id = ?
        ");


        $stmt->execute([
            $requestId
        ]);


        $_SESSION['success'] =
            "Password reset request rejected successfully.";


        header(
            "Location: password-reset-requests.php"
        );

        exit();

    }


    /*
    |--------------------------------------------------------------------------
    | Invalid Action
    |--------------------------------------------------------------------------
    */

    $_SESSION['error'] =
        "Invalid password reset action.";

    header(
        "Location: password-reset-requests.php"
    );

    exit();

}


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

$allowedStatuses = [

    'all',
    'pending',
    'approved',
    'completed',
    'rejected',
    'expired'

];


$selectedStatus =
    trim(
        $_GET['status'] ?? 'all'
    );


if (
    !in_array(
        $selectedStatus,
        $allowedStatuses,
        true
    )
) {

    $selectedStatus = 'all';

}


/*
|--------------------------------------------------------------------------
| Summary Counts
|--------------------------------------------------------------------------
*/

$summaryStmt = $pdo->query("
    SELECT

        COUNT(*) AS total,

        SUM(
            CASE
                WHEN status = 'pending'
                THEN 1
                ELSE 0
            END
        ) AS pending_count,

        SUM(
            CASE
                WHEN status = 'approved'
                THEN 1
                ELSE 0
            END
        ) AS approved_count,

        SUM(
            CASE
                WHEN status = 'completed'
                THEN 1
                ELSE 0
            END
        ) AS completed_count

    FROM password_reset_requests
");


$summary =
    $summaryStmt->fetch(
        PDO::FETCH_ASSOC
    );


/*
|--------------------------------------------------------------------------
| Pagination
|--------------------------------------------------------------------------
*/

$resetRequestsPerPage = 15;


$resetRequestPage =
    max(
        1,
        (int)($_GET['page'] ?? 1)
    );


$whereSql = "";

$queryParams = [];


if ($selectedStatus !== 'all') {

    $whereSql =
        " WHERE prr.status = ? ";

    $queryParams[] =
        $selectedStatus;

}


/*
|--------------------------------------------------------------------------
| Count Filtered Requests
|--------------------------------------------------------------------------
*/

$countStmt = $pdo->prepare("
    SELECT COUNT(*)

    FROM password_reset_requests prr

    {$whereSql}
");


$countStmt->execute(
    $queryParams
);


$totalResetRequests =
    (int)$countStmt->fetchColumn();


$totalResetPages =
    max(
        1,
        (int)ceil(
            $totalResetRequests /
            $resetRequestsPerPage
        )
    );


if (
    $resetRequestPage >
    $totalResetPages
) {

    $resetRequestPage =
        $totalResetPages;

}


$resetRequestOffset =
    ($resetRequestPage - 1)
    * $resetRequestsPerPage;


/*
|--------------------------------------------------------------------------
| Get Reset Requests
|--------------------------------------------------------------------------
*/

$sql = "
    SELECT

        prr.id,
        prr.user_id,
        prr.phone,
        prr.email,
        prr.request_type,
        prr.status,
        prr.requested_at,
        prr.approved_at,
        prr.completed_at,
        prr.token_expires_at,

        u.fullname,
        u.role,
        u.status AS user_status

    FROM password_reset_requests prr

    INNER JOIN users u
        ON u.id = prr.user_id

    {$whereSql}

    ORDER BY prr.requested_at DESC

    LIMIT {$resetRequestsPerPage}
    OFFSET {$resetRequestOffset}
";


$stmt = $pdo->prepare($sql);

$stmt->execute(
    $queryParams
);


$resetRequests =
    $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>
    Password Reset Requests - Complete Bliss
</title>


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

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

<link
    rel="stylesheet"
    href="../assets/css/admin-password-resets.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="password-reset-admin-page">


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

    <div class="password-reset-page-header">


        <div>

            <span class="reset-header-label">

                <i class="fas fa-shield-halved"></i>

                ACCOUNT SECURITY

            </span>


            <h1>
                Password Reset Requests
            </h1>


            <p>
                Review and securely approve member
                account recovery requests.
            </p>

        </div>


        <div class="password-reset-header-icon">

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

        </div>


    </div>



    <!-- =====================================================
         SUMMARY
    ====================================================== -->

    <section class="reset-summary-grid">


        <div class="reset-summary-card">


            <div class="reset-summary-icon total">

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

            </div>


            <div>

                <span>
                    Total Requests
                </span>

                <strong>

                    <?= number_format(
                        (int)($summary['total'] ?? 0)
                    ); ?>

                </strong>

            </div>


        </div>



        <div class="reset-summary-card">


            <div class="reset-summary-icon pending">

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

            </div>


            <div>

                <span>
                    Awaiting Review
                </span>

                <strong>

                    <?= number_format(
                        (int)($summary['pending_count'] ?? 0)
                    ); ?>

                </strong>

            </div>


        </div>



        <div class="reset-summary-card">


            <div class="reset-summary-icon approved">

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

            </div>


            <div>

                <span>
                    Approved
                </span>

                <strong>

                    <?= number_format(
                        (int)($summary['approved_count'] ?? 0)
                    ); ?>

                </strong>

            </div>


        </div>



        <div class="reset-summary-card">


            <div class="reset-summary-icon completed">

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

            </div>


            <div>

                <span>
                    Completed
                </span>

                <strong>

                    <?= number_format(
                        (int)($summary['completed_count'] ?? 0)
                    ); ?>

                </strong>

            </div>


        </div>


    </section>



    <!-- =====================================================
         INFO
    ====================================================== -->

    <div class="reset-security-note">


        <div>

            <i class="fas fa-circle-info"></i>

        </div>


        <p>
            Verify the member's identity before approving
            a request. The system will generate a one-time
            reset code that expires after
            <strong>30 minutes</strong>.
            The member creates their own new password,
            so the admin never needs to know it.
        </p>


    </div>



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

    <section class="reset-toolbar">


        <div>

            <h2>
                Recovery Requests
            </h2>


            <p>
                <?= number_format(
                    $totalResetRequests
                ); ?>
                request<?= $totalResetRequests === 1
                    ? ''
                    : 's'; ?>
                found
            </p>

        </div>



        <form
            method="GET"
            action=""
            class="reset-filter-form"
        >


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


            <select
                name="status"
                onchange="this.form.submit()"
            >


                <option
                    value="all"
                    <?= $selectedStatus === 'all'
                        ? 'selected'
                        : ''; ?>
                >
                    All Requests
                </option>


                <option
                    value="pending"
                    <?= $selectedStatus === 'pending'
                        ? 'selected'
                        : ''; ?>
                >
                    Pending
                </option>


                <option
                    value="approved"
                    <?= $selectedStatus === 'approved'
                        ? 'selected'
                        : ''; ?>
                >
                    Approved
                </option>


                <option
                    value="completed"
                    <?= $selectedStatus === 'completed'
                        ? 'selected'
                        : ''; ?>
                >
                    Completed
                </option>


                <option
                    value="rejected"
                    <?= $selectedStatus === 'rejected'
                        ? 'selected'
                        : ''; ?>
                >
                    Rejected
                </option>


                <option
                    value="expired"
                    <?= $selectedStatus === 'expired'
                        ? 'selected'
                        : ''; ?>
                >
                    Expired
                </option>


            </select>


        </form>


    </section>



    <!-- =====================================================
         REQUESTS
    ====================================================== -->

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


        <section class="reset-request-list">


            <?php foreach ($resetRequests as $request): ?>


                <article class="reset-request-card">


                    <!-- MEMBER -->

                    <div class="reset-member-info">


                        <div class="reset-member-avatar">

                            <?= htmlspecialchars(
                                strtoupper(
                                    substr(
                                        $request['fullname'],
                                        0,
                                        1
                                    )
                                )
                            ); ?>

                        </div>


                        <div>


                            <h3>

                                <?= htmlspecialchars(
                                    $request['fullname']
                                ); ?>

                            </h3>


                            <span>

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

                                <?= htmlspecialchars(
                                    $request['phone']
                                ); ?>

                            </span>


                            <?php if (
                                !empty($request['email'])
                            ): ?>

                                <span>

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

                                    <?= htmlspecialchars(
                                        $request['email']
                                    ); ?>

                                </span>

                            <?php endif; ?>


                        </div>


                    </div>



                    <!-- REQUEST DETAILS -->

                    <div class="reset-request-details">


                        <div>

                            <span>
                                Requested
                            </span>


                            <strong>

                                <?= date(
                                    'd M Y, h:i A',
                                    strtotime(
                                        $request['requested_at']
                                    )
                                ); ?>

                            </strong>

                        </div>



                        <div>

                            <span>
                                Recovery Type
                            </span>


                            <strong>

                                <?= ucfirst(
                                    htmlspecialchars(
                                        $request['request_type']
                                    )
                                ); ?>

                            </strong>

                        </div>



                        <?php if (
                            !empty(
                                $request['token_expires_at']
                            ) &&
                            $request['status'] === 'approved'
                        ): ?>


                            <div>

                                <span>
                                    Code Expires
                                </span>


                                <strong>

                                    <?= date(
                                        'd M, h:i A',
                                        strtotime(
                                            $request['token_expires_at']
                                        )
                                    ); ?>

                                </strong>

                            </div>


                        <?php endif; ?>


                    </div>



                    <!-- STATUS -->

                    <div class="reset-request-status">


                        <span
                            class="reset-status
                            reset-status-<?= htmlspecialchars(
                                $request['status']
                            ); ?>"
                        >

                            <?php

                            $statusIcons = [

                                'pending' =>
                                    'fa-clock',

                                'approved' =>
                                    'fa-key',

                                'completed' =>
                                    'fa-circle-check',

                                'rejected' =>
                                    'fa-circle-xmark',

                                'expired' =>
                                    'fa-hourglass-end'

                            ];

                            ?>


                            <i class="fas <?= htmlspecialchars(
                                $statusIcons[
                                    $request['status']
                                ] ?? 'fa-circle'
                            ); ?>"></i>


                            <?= ucfirst(
                                htmlspecialchars(
                                    $request['status']
                                )
                            ); ?>

                        </span>


                    </div>



                    <!-- ACTIONS -->

                    <div class="reset-request-actions">


                        <?php if (
                            $request['status']
                            === 'pending'
                        ): ?>


                            <form
                                method="POST"
                                class="reset-action-form"
                            >

                                <input
                                    type="hidden"
                                    name="csrf_token"
                                    value="<?= htmlspecialchars(
                                        $_SESSION[
                                            'password_reset_csrf'
                                        ]
                                    ); ?>"
                                >


                                <input
                                    type="hidden"
                                    name="request_id"
                                    value="<?= (int)$request['id']; ?>"
                                >


                                <input
                                    type="hidden"
                                    name="action"
                                    value="approve"
                                >


                                <button
                                    type="submit"
                                    class="reset-approve-btn"
                                >

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

                                    Approve

                                </button>

                            </form>


                        <?php endif; ?>



                        <?php if (
                            in_array(
                                $request['status'],
                                [
                                    'pending',
                                    'approved'
                                ],
                                true
                            )
                        ): ?>


                            <form
                                method="POST"
                                class="reset-action-form reject-reset-form"
                            >

                                <input
                                    type="hidden"
                                    name="csrf_token"
                                    value="<?= htmlspecialchars(
                                        $_SESSION[
                                            'password_reset_csrf'
                                        ]
                                    ); ?>"
                                >


                                <input
                                    type="hidden"
                                    name="request_id"
                                    value="<?= (int)$request['id']; ?>"
                                >


                                <input
                                    type="hidden"
                                    name="action"
                                    value="reject"
                                >


                                <button
                                    type="submit"
                                    class="reset-reject-btn"
                                >

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

                                    Reject

                                </button>

                            </form>


                        <?php endif; ?>



                        <?php if (
                            !in_array(
                                $request['status'],
                                [
                                    'pending',
                                    'approved'
                                ],
                                true
                            )
                        ): ?>


                            <span class="reset-action-finished">

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

                                Closed

                            </span>


                        <?php endif; ?>


                    </div>


                </article>


            <?php endforeach; ?>


        </section>



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

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


            <nav class="reset-pagination">


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


                    <a
                        href="?status=<?= urlencode(
                            $selectedStatus
                        ); ?>&page=<?= $resetRequestPage - 1; ?>"
                    >

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

                        Previous

                    </a>


                <?php endif; ?>



                <span>

                    Page

                    <strong>
                        <?= $resetRequestPage; ?>
                    </strong>

                    of

                    <strong>
                        <?= $totalResetPages; ?>
                    </strong>

                </span>



                <?php if (
                    $resetRequestPage <
                    $totalResetPages
                ): ?>


                    <a
                        href="?status=<?= urlencode(
                            $selectedStatus
                        ); ?>&page=<?= $resetRequestPage + 1; ?>"
                    >

                        Next

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

                    </a>


                <?php endif; ?>


            </nav>


        <?php endif; ?>


    <?php else: ?>


        <!-- EMPTY -->

        <div class="reset-empty-state">


            <div>

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

            </div>


            <h2>
                No Reset Requests
            </h2>


            <p>
                There are currently no password recovery
                requests matching this filter.
            </p>


        </div>


    <?php endif; ?>


</main>


</div>



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


<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>



<!-- =========================================================
     RESET CODE GENERATED
========================================================= -->

<?php if (
    isset(
        $_SESSION['reset_code_created']
    )
): ?>


<?php

$codeData =
    $_SESSION['reset_code_created'];


$resetCodeHtml = '

<div style="
    text-align:center;
    padding-top:5px;
">

    <p style="
        color:#667085;
        font-size:13px;
        line-height:1.7;
    ">
        Verify the member before giving them this
        one-time password reset code.
    </p>

    <div style="
        margin:18px 0;
        padding:17px;
        border-radius:12px;
        background:#eff6ff;
        border:1px solid #bfdbfe;
    ">

        <small style="
            display:block;
            color:#667085;
            margin-bottom:5px;
        ">
            MEMBER
        </small>

        <strong style="
            display:block;
            color:#101828;
            margin-bottom:14px;
        ">'
            .
            htmlspecialchars(
                $codeData['member']
            )
            .
        '</strong>

        <small style="
            display:block;
            color:#667085;
            margin-bottom:5px;
        ">
            ONE-TIME RESET CODE
        </small>

        <strong
            id="generatedResetCode"
            style="
                display:block;
                font-size:27px;
                letter-spacing:2px;
                color:#2563eb;
            "
        >'
            .
            htmlspecialchars(
                $codeData['code']
            )
            .
        '</strong>

    </div>

    <p style="
        color:#98a2b3;
        font-size:11px;
    ">
        This code expires in 30 minutes
        and can only be used once.
    </p>

</div>

';

?>


<script>

document.addEventListener(
    "DOMContentLoaded",
    function () {

        Swal.fire({

            icon:
                "success",

            title:
                "Reset Approved",

            html:
                <?= json_encode(
                    $resetCodeHtml
                ); ?>,

            confirmButtonText:
                "Copy Code",

            confirmButtonColor:
                "#2563eb",

            showCancelButton:
                true,

            cancelButtonText:
                "Close"

        }).then(function (result) {

            if (
                result.isConfirmed
            ) {

                const codeElement =
                    document.getElementById(
                        "generatedResetCode"
                    );


                if (codeElement) {

                    navigator.clipboard
                        .writeText(
                            codeElement
                                .innerText
                                .trim()
                        )
                        .then(function () {

                            Swal.fire({

                                icon:
                                    "success",

                                title:
                                    "Copied",

                                text:
                                    "Reset code copied successfully.",

                                timer:
                                    1300,

                                showConfirmButton:
                                    false

                            });

                        });

                }

            }

        });

    }
);

</script>


<?php

unset(
    $_SESSION['reset_code_created']
);

endif;

?>



<!-- SUCCESS -->

<?php if (
    isset($_SESSION['success'])
): ?>

<script>

document.addEventListener(
    "DOMContentLoaded",
    function () {

        Swal.fire({

            icon:
                "success",

            title:
                "Successful",

            text:
                <?= json_encode(
                    $_SESSION['success']
                ); ?>,

            confirmButtonColor:
                "#2563eb"

        });

    }
);

</script>

<?php

unset($_SESSION['success']);

endif;

?>



<!-- ERROR -->

<?php if (
    isset($_SESSION['error'])
): ?>

<script>

document.addEventListener(
    "DOMContentLoaded",
    function () {

        Swal.fire({

            icon:
                "error",

            title:
                "Unable to Continue",

            text:
                <?= json_encode(
                    $_SESSION['error']
                ); ?>,

            confirmButtonColor:
                "#dc3545"

        });

    }
);

</script>

<?php

unset($_SESSION['error']);

endif;

?>



<!-- REJECT CONFIRMATION -->

<script>

document.addEventListener(
    "DOMContentLoaded",
    function () {

        const rejectForms =
            document.querySelectorAll(
                ".reject-reset-form"
            );


        rejectForms.forEach(
            function (form) {

                form.addEventListener(
                    "submit",
                    function (event) {

                        event.preventDefault();


                        Swal.fire({

                            icon:
                                "warning",

                            title:
                                "Reject Reset Request?",

                            text:
                                "Any approved reset code for this request will become unusable.",

                            showCancelButton:
                                true,

                            confirmButtonText:
                                "Yes, Reject",

                            cancelButtonText:
                                "Cancel",

                            confirmButtonColor:
                                "#dc3545"

                        }).then(
                            function (result) {

                                if (
                                    result.isConfirmed
                                ) {

                                    form.submit();

                                }

                            }
                        );

                    }
                );

            }
        );

    }
);

</script>


</body>

</html>