<?php

session_start();

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


/* =========================================================
   ONLY ALLOW POST
========================================================= */

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

    header('Location: ../forgot-password.php');
    exit();

}


/* =========================================================
   GET PHONE
========================================================= */

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


$_SESSION['old_reset_phone'] = $phone;


if ($phone === '') {

    $_SESSION['reset_error'] =
        'Please enter your registered phone number.';

    header('Location: ../forgot-password.php');
    exit();

}


/* =========================================================
   FIND USER
========================================================= */

$stmt = $pdo->prepare(
    "
    SELECT
        id,
        fullname,
        phone,
        email,
        status
    FROM users
    WHERE phone = ?
    LIMIT 1
    "
);

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

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


/* =========================================================
   DO NOT REVEAL WHETHER AN ACCOUNT EXISTS
========================================================= */

if (!$user) {

    /*
     * We deliberately show a general message rather than:
     * "Phone number not found".
     *
     * This prevents people from testing phone numbers
     * to discover who has a Complete Bliss account.
     */

    $_SESSION['reset_message'] =
        'If the phone number belongs to a Complete Bliss account, a password recovery request has been submitted.';

    unset($_SESSION['old_reset_phone']);

    header('Location: ../forgot-password.php');
    exit();

}


/* =========================================================
   ACCOUNT STATUS
========================================================= */

if ($user['status'] === 'suspended') {

    $_SESSION['reset_error'] =
        'This account is currently suspended. Please contact Complete Bliss support for assistance.';

    header('Location: ../forgot-password.php');
    exit();

}


/* =========================================================
   CHECK RECENT REQUEST
========================================================= */

$recentRequest = $pdo->prepare(
    "
    SELECT id
    FROM password_reset_requests

    WHERE
        user_id = ?
        AND status IN ('pending', 'approved')
        AND requested_at >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)

    ORDER BY id DESC

    LIMIT 1
    "
);

$recentRequest->execute([
    $user['id']
]);

$existingRequest =
    $recentRequest->fetch(PDO::FETCH_ASSOC);


/* =========================================================
   DON'T CREATE DUPLICATE REQUESTS
========================================================= */

if ($existingRequest) {

    $_SESSION['reset_message'] =
        'A password recovery request already exists for this account. Please wait for Complete Bliss support to process it.';

    unset($_SESSION['old_reset_phone']);

    header('Location: ../forgot-password.php');
    exit();

}


/* =========================================================
   EXPIRE OLD UNUSED REQUESTS
========================================================= */

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

    SET status = 'expired'

    WHERE
        user_id = ?
        AND status IN ('pending', 'approved')
    "
);

$expireOld->execute([
    $user['id']
]);


/* =========================================================
   CREATE NEW ADMIN-ASSISTED REQUEST
========================================================= */

$createRequest = $pdo->prepare(
    "
    INSERT INTO password_reset_requests
    (
        user_id,
        phone,
        email,
        request_type,
        status
    )

    VALUES
    (
        :user_id,
        :phone,
        :email,
        'admin',
        'pending'
    )
    "
);


$createRequest->execute([

    'user_id' =>
        $user['id'],

    'phone' =>
        $user['phone'],

    'email' =>
        !empty($user['email'])
            ? $user['email']
            : null

]);


/* =========================================================
   SUCCESS
========================================================= */

$_SESSION['reset_message'] =
    'Your password recovery request has been submitted successfully. Complete Bliss support will verify your account before a reset code is issued.';


unset($_SESSION['old_reset_phone']);


header('Location: ../forgot-password.php');

exit();