<?php
require_once '../includes/config.php';
require_once 'helpers.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// PHPMailer files
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsAlert(
        'Invalid Request',
        'This action is not allowed.',
        'error',
        '../sign-in.php'
    );
}

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

if ($email === '') {
    jsAlert(
        'Missing Email',
        'Please enter your registered email address.',
        'warning',
        '../sign-in.php'
    );
}

try {
    /* =========================
       1. CHECK USER EXISTS
    ========================== */
    $stmt = $conn->prepare("
        SELECT id, name 
        FROM users 
        WHERE email = ? 
        LIMIT 1
    ");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        jsAlert(
            'Account Not Found',
            'No account is associated with this email address.',
            'error',
            '../sign-in.php'
        );
    }

    $user = $result->fetch_assoc();

    /* =========================
       2. GENERATE TOKEN
    ========================== */
    $token       = bin2hex(random_bytes(32));      // sent via email
    $hashedToken = hash('sha256', $token);         // stored in DB

    /* =========================
       3. INSERT / UPDATE RESET
    ========================== */
    $stmt = $conn->prepare("
        SELECT id 
        FROM password_resets 
        WHERE user_id = ?
        LIMIT 1
    ");
    $stmt->bind_param("i", $user['id']);
    $stmt->execute();
    $resetResult = $stmt->get_result();

    if ($resetResult->num_rows > 0) {
        $stmt = $conn->prepare("
            UPDATE password_resets
            SET token = ?, 
                expires_at = DATE_ADD(NOW(), INTERVAL 1 HOUR)
            WHERE user_id = ?
        ");
        $stmt->bind_param("si", $hashedToken, $user['id']);
    } else {
        $stmt = $conn->prepare("
            INSERT INTO password_resets (user_id, token, expires_at)
            VALUES (?, ?, DATE_ADD(NOW(), INTERVAL 1 HOUR))
        ");
        $stmt->bind_param("is", $user['id'], $hashedToken);
    }
    $stmt->execute();

    /* =========================
       4. RESET LINK
    ========================== */
    $resetLink = "http://localhost/finvoicer/invoice360/reset-password.php?token={$token}";

    /* =========================
       5. SEND EMAIL
    ========================== */
    $mail = new PHPMailer(true);

    $mail->isSMTP();
    $mail->Host       = 'smtppro.zoho.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'docsupport@docadvisory.com';
    $mail->Password   = 'DegitechSolutions@2025'; // move to env later
    $mail->SMTPSecure = 'ssl';
    $mail->Port       = 465;

    $mail->setFrom('docsupport@docadvisory.com', 'Finvoicer Support');
    $mail->addAddress($email, $user['name']);

    $mail->isHTML(true);
    $mail->Subject = 'Password Reset Request';
    $mail->Body = <<<HTML
<div style="font-family:Arial,Helvetica,sans-serif;background:#f4f6f8;padding:30px">
    <div style="max-width:520px;background:#ffffff;margin:auto;border-radius:10px;
                padding:30px;box-shadow:0 10px 30px rgba(0,0,0,0.08)">

        <h2 style="color:#2c5364;text-align:center;margin-top:0">
            Password Reset Request
        </h2>

        <p>Dear {$user['name']},</p>

        <p>
            We received a request to reset the password associated with your account.
            Please click the button below to proceed.
        </p>

        <p style="text-align:center;margin:30px 0">
            <a href="{$resetLink}"
               style="background:#2c5364;color:#ffffff;padding:14px 28px;
                      text-decoration:none;border-radius:8px;
                      font-weight:bold;display:inline-block">
                Reset Password
            </a>
        </p>

        <p style="font-size:13px">
            If the button does not work, copy and paste the link below into your browser:
        </p>

        <p style="font-size:12px;word-break:break-all;color:#2c5364">
            {$resetLink}
        </p>

        <p style="font-size:13px">
            This link will expire in <strong>1 hour</strong>.
        </p>

        <hr>

        <p style="font-size:12px;color:#777">
            If you did not request this password reset, please ignore this email.
            Your account remains secure.
        </p>

        <p style="font-size:12px;color:#777">
            Regards,<br>
            <strong>Finvoicer Support Team</strong>
        </p>

    </div>
</div>
HTML;

    $mail->send();

    jsAlert(
        'Email Sent',
        'A password reset link has been sent to your email address.',
        'success',
        '../sign-in.php'
    );

} catch (Exception $e) {
    error_log($e->getMessage());

    jsAlert(
        'Error',
        'Unable to process your request at the moment. Please try again later.',
        'error'
    );
}
