<?php
session_start();

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

require '../../PHPMailer/src/Exception.php';
require '../../PHPMailer/src/PHPMailer.php';
require '../../PHPMailer/src/SMTP.php';
include '../../assets/constant/config.php';

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    function generateRandomCode($length = 10)
    {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $code = '';
        $maxIndex = strlen($characters) - 1;

        for ($i = 0; $i < $length; $i++) {
            $randomIndex = mt_rand(0, $maxIndex);
            $code .= $characters[$randomIndex];
        }

        return $code;
    }

    if (isset($_POST['submit1'])) {
        $stmt2 = $conn->prepare("SELECT * FROM `user` WHERE delete_status='0' AND email = :email");
        $stmt2->bindParam(':email', $_POST['email']);
        $stmt2->execute();
        $record2 = $stmt2->fetchAll();

        if (count($record2) <= 0) {
            if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] == UPLOAD_ERR_OK) {
                $filepath = "../../assets/images/" . htmlspecialchars($_FILES["photo"]["name"], ENT_QUOTES, 'UTF-8');

                if (move_uploaded_file($_FILES["photo"]["tmp_name"], $filepath)) {
                    $img = htmlspecialchars($_FILES["photo"]["name"], ENT_QUOTES, 'UTF-8');
                } else {
                    echo "Error !!";
                    exit;
                }
            } else {
                echo "File upload error";
                exit;
            }

            $pass = hash('sha256', $_POST['password']);
            $pass1 = hash('sha256', $_POST['repassword']);

            function createSalt()
            {
                return '2123293dsj2hu2nikhiljdsd';
            }
            $salt = createSalt();
            $password = hash('sha256', $salt . $pass);
            $repassword = hash('sha256', $salt . $pass1);

            $username = $_POST["username"];
            $gender = $_POST["gender"];
            $mobileno = $_POST["mobileno"];
            $email = $_POST["email"];
            $role = $_POST["role"];
            $address = $_POST["address"];
            $notes = $_POST["notes"];
            $otp = rand(100000, 999999);
            $randomCode = generateRandomCode();

            $stmt = $conn->prepare("INSERT INTO `user` (username, gender, photo, mobileno, email, password, repassword, role, address, notes, otp, random, auth)
                                    VALUES (:username, :gender, :photo, :mobileno, :email, :password, :repassword, :role, :address, :notes, :otp, :random, '1')");
            $stmt->bindParam(':username', $username);
            $stmt->bindParam(':gender', $gender);
            $stmt->bindParam(':photo', $img);
            $stmt->bindParam(':mobileno', $mobileno);
            $stmt->bindParam(':email', $email);
            $stmt->bindParam(':password', $password);
            $stmt->bindParam(':repassword', $repassword);
            $stmt->bindParam(':role', $role);
            $stmt->bindParam(':address', $address);
            $stmt->bindParam(':notes', $notes);
            $stmt->bindParam(':otp', $otp);
            $stmt->bindParam(':random', $randomCode);
            $stmt->execute();

            $msg1 = "Dear " . $username . ",\n\nYour One-Time Password (OTP) for user is: " . $otp . "\n\nPlease use this OTP to complete your login process.\n\nThank you,\n";

            $stmt = $conn->prepare("SELECT * FROM `emailsetting`");
            $stmt->execute();
            $result = $stmt->fetchAll();
            foreach ($result as $row) {
                $smtp_server = $row['smtp_server'];
                $smtp_password = $row['smtp_password'];
                $smtp_enc = $row['smtp_type'];
                $smtp_username = $row['smtp_username'];
                $smtp_port = $row['stmp_port'];
            }

            $dt = date('Y-m-d H:i:s');
            $mail = new PHPMailer(true);

            $mail->isSMTP();
            $mail->Host = $smtp_server;
            $mail->SMTPAuth = true;
            $mail->Username = $smtp_username;
            $mail->Password = $smtp_password;
            $mail->SMTPSecure = $smtp_enc;
            $mail->Port = $smtp_port;

            $mail->setFrom($smtp_username);
            $mail->addAddress($_POST['email']);

            $mail->isHTML(true);
            $mail->Subject = 'OTP on ' . $dt;
            $mail->Body = $msg1;
            $mail->AltBody = $msg1;

            if ($mail->send()) {
                $_SESSION['success'] = "success";
                header("location:../otp.php?otp=" . $randomCode);
                exit;
            } else {
                echo "Error sending email";
            }
        } else {
            echo '<link rel="stylesheet" href="../popup_style.css">
            <div class="popup popup--icon -error js_error-popup popup--visible">
                <div class="popup__background"></div>
                <div class="popup__content">
                    <h3 class="popup__content__title">
                        Error
                    </h3>
                    <p>Sorry, Your Email id is already registered.</p>
                    <p>
                        <a href="../../index.php"><button class="button button--error" data-for="js_error-popup">Close</button></a>
                    </p>
                </div>
            </div>';
        }
    }

    if (isset($_POST['submit'])) {
        $input1 = $_POST['input1'];
        $input2 = $_POST['input2'];
        $input3 = $_POST['input3'];
        $input4 = $_POST['input4'];
        $input5 = $_POST['input5'];
        $input6 = $_POST['input6'];
        $pin = $input1 . $input2 . $input3 . $input4 . $input5 . $input6;

        $stmt = $conn->prepare("SELECT * FROM `user` WHERE random = :random AND otp = :otp");
        $stmt->bindParam(':random', $_POST['code']);
        $stmt->bindParam(':otp', $pin);
        $stmt->execute();
        $row = $stmt->fetchAll();
        $cont = count($row);

        if ($cont == 0) {
            echo '<link rel="stylesheet" href="../popup_style.css">
            <div class="popup popup--icon -error js_error-popup popup--visible">
                <div class="popup__background"></div>
                <div class="popup__content">
                    <h3 class="popup__content__title">
                        Error
                    </h3>
                    <p>You may have entered wrong OTP. Please try again.</p>
                    <p>
                        <a href="../otp.php?otp=' . $_POST['code'] . '"><button class="button button--error" data-for="js_error-popup">Close</button></a>
                    </p>
                </div>
            </div>';
        } else {
            $stmt = $conn->prepare("UPDATE `user` SET status='1', delete_status='0' WHERE random = :random");
            $stmt->bindParam(':random', $_POST['code']);
            $stmt->execute();

            $stmt2 = $conn->prepare("SELECT * FROM user WHERE random = :random AND otp = :otp");
            $stmt2->bindParam(':random', $_POST['code']);
            $stmt2->bindParam(':otp', $pin);
            $stmt2->execute();
            $record2 = $stmt2->fetch();

            $stmt1 = $conn->prepare("INSERT INTO `login`(`email`, `password`, `username`, `mobileno`,`role`) VALUES (:email, :password, :username, :mobileno, :role)");
            $stmt1->bindParam(':email', $record2['email']);
            $stmt1->bindParam(':password', $record2['password']);
            $stmt1->bindParam(':username', $record2['username']);
            $stmt1->bindParam(':mobileno', $record2['mobileno']);
            $stmt1->bindParam(':role', $record2['role']);
            $stmt1->execute();

            $_SESSION['success'] = "success";
            echo '<div class="popup popup--icon -success js_success-popup popup--visible">
            <div class="popup__background"></div>
            <div class="popup__content">
                <h3 class="popup__content__title">
                    Success
                </h3>
                <p> Your Email is verified</p>
                <p>
                    <script>setTimeout("location.href = \'../../index.php\';",1500);</script>
                </p>
            </div>
            </div>';
        }
    }

    if (isset($_POST['del_id'])) {
        $stmt = $conn->prepare("UPDATE `user` SET auth='0' WHERE id = :id");
        $stmt->bindParam(':id', $_POST['del_id']);
        $stmt->execute();

        $_SESSION['success'] = "Successfully blocked the user";
        header("location:../manage_user.php");
    }

    if (isset($_POST['con_id'])) {
        $stmt = $conn->prepare("UPDATE `user` SET auth='1' WHERE id = :id");
        $stmt->bindParam(':id', $_POST['con_id']);
        $stmt->execute();

        $_SESSION['success'] = "Successfully approved the user";
        header("location:../manage_user.php");
    }
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>