<?php

require_once __DIR__ . "/../includes/db.php";
require_once __DIR__ . "/../includes/functions.php";
require_once __DIR__ . "/../includes/mailer.php";

/**
 * =========================================
 * DEMOBANK OTP SERVICE
 * =========================================
 * - Generate OTP
 * - Verify OTP
 * - Reuse for transfer, login, reset, etc.
 */

class OTPService {

    protected $conn;
    protected $otpLength = 6;      // 6-digit OTP
    protected $expiryMinutes = 5;  // 5 minutes expiration

    public function __construct() {
        $this->conn = db();
    }

    /**
     * Generate OTP for a user
     */
    public function generateOTP($user_id) {

        // Generate 6-digit OTP
        $otp = random_int(100000, 999999);

        $expires_at = date("Y-m-d H:i:s", strtotime("+{$this->expiryMinutes} minutes"));

        // Save OTP to database
        $stmt = $this->conn->prepare("
            INSERT INTO otp_codes (user_id, otp_code, expires_at, created_at)
            VALUES (?, ?, ?, NOW())
        ");
        $stmt->bind_param("iss", $user_id, $otp, $expires_at);
        $stmt->execute();

        // Fetch user email and name
        $stmt = $this->conn->prepare("SELECT email, full_name FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();

        if ($user) {
            // Send OTP via email
            $subject = "DemoBank Security OTP";
            $message = "
            <html>
            <body>
                <h2>DemoBank Security OTP</h2>
                <p>Hello <b>{$user['full_name']}</b>,</p>
                <p>Your One-Time Password (OTP) is:</p>
                <h1 style='letter-spacing:5px;'>{$otp}</h1>
                <p>This code will expire in <b>{$this->expiryMinutes} minutes</b>.</p>
                <p>If you did not request this, please ignore this email.</p>
                <br>
                <p>DemoBank Security Team</p>
            </body>
            </html>
            ";
            sendEmail($user['email'], $subject, $message);
        }

        return $otp;
    }

    /**
     * Verify OTP for a user
     */
    public function verifyOTP($user_id, $otp) {

        $stmt = $this->conn->prepare("
            SELECT id, expires_at, used 
            FROM otp_codes 
            WHERE user_id = ? AND otp_code = ? 
            ORDER BY created_at DESC LIMIT 1
        ");
        $stmt->bind_param("is", $user_id, $otp);
        $stmt->execute();
        $result = $stmt->get_result();
        $record = $result->fetch_assoc();

        if (!$record) {
            return ["status" => false, "message" => "Invalid OTP"];
        }

        if ($record['used']) {
            return ["status" => false, "message" => "OTP already used"];
        }

        if (strtotime($record['expires_at']) < time()) {
            return ["status" => false, "message" => "OTP expired"];
        }

        // Mark OTP as used
        $stmt = $this->conn->prepare("UPDATE otp_codes SET used = 1 WHERE id = ?");
        $stmt->bind_param("i", $record['id']);
        $stmt->execute();

        return ["status" => true, "message" => "OTP verified"];
    }

    /**
     * Optional: Delete expired OTPs
     */
    public function cleanupExpiredOTPs() {
        $stmt = $this->conn->prepare("
            DELETE FROM otp_codes WHERE expires_at < NOW() OR used = 1
        ");
        $stmt->execute();
    }
}