<?php

include "../classes/db.class.php";
include "../classes/email.class.php";

// check if email exists
$db = new db();
$email_res = $db->query("SELECT * FROM users WHERE email = '{$_POST['email']}'");
if ($email_res->num_rows == 0) {
    exit;
} else {
    // create otp
    $OTP = rand(1, 99999);
    // $OTP = 1;
    // create record in database
    $db->query("INSERT INTO otp (`email`, `otp`) VALUES ('{$_POST['email']}', '" . hash('sha256', $OTP) . "')");

    $email = new email();
    $name = explode('@', $_POST['email']);
    $email->add_address($_POST['email'], $name[0]);
    $email->subject("PASSWORD CHANGE OTP");

    $email->body("
        <html>
        <head>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background-color: #f4f4f4;
                    margin: 0;
                    padding: 0;
                }
                .container {
                    max-width: 600px;
                    margin: 20px auto;
                    background-color: #ffffff;
                    padding: 20px;
                    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                }
                .header {
                    background-color: #007bff;
                    color: #ffffff;
                    padding: 10px 0;
                    text-align: center;
                }
                .content {
                    margin-top: 20px;
                }
                .otp {
                    font-size: 1.5em;
                    color: #333333;
                }
                .footer {
                    margin-top: 20px;
                    text-align: center;
                    font-size: 0.9em;
                    color: #666666;
                }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h2>Password Change Request</h2>
                </div>
                <div class='content'>
                    <p>Dear {$name[0]},</p>
                    <p>We received a request to change your password. Please use the following OTP to proceed with the password change:</p>
                    <p class='otp'>{$OTP}</p>
                    <p>If you did not request a password change, please ignore this email.</p>
                </div>
                <div class='footer'>
                    <p>Thank you,<br>Unleashed K9 Solutions</p>
                </div>
            </div>
        </body>
        </html>
    ");

    if ($email->send()) {
        echo hash('sha256', $OTP);
    }
}
