<?php
session_start();
include "../../connect/db.php";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $firstname = $mysqli->real_escape_string($_POST['firstname']);
    $lastname = $mysqli->real_escape_string($_POST['lastname']);
    $middlename = $mysqli->real_escape_string($_POST['middlename']);
    $nickname = $mysqli->real_escape_string($_POST['nickname']);
    $email = $mysqli->real_escape_string($_POST['email']);
    $phone = $mysqli->real_escape_string($_POST['phone']);
    $dob = $mysqli->real_escape_string($_POST['dob']);
    $zipcode = $mysqli->real_escape_string($_POST['zipcode']);
    $title = $mysqli->real_escape_string($_POST['title']);
    $gender = $mysqli->real_escape_string($_POST['gender']);
    $address = $mysqli->real_escape_string($_POST['address']);
    $country = $mysqli->real_escape_string($_POST['country']);
    $state = $mysqli->real_escape_string($_POST['state']);
    $city = $mysqli->real_escape_string($_POST['city']);
    $ssn = $mysqli->real_escape_string($_POST['ssn']);
    $usercurrency = $mysqli->real_escape_string($_POST['usercurrency']);
    $account_type = $mysqli->real_escape_string($_POST['account_type']);
    $password = $mysqli->real_escape_string($_POST['password']);

    $query = $mysqli->query("SELECT email FROM users WHERE email = '$email'");

    if ($query->num_rows == 0) {
        $seed = str_split('0123456789');
        shuffle($seed);
        $rand = '';
        foreach (array_rand($seed, 10) as $k) $rand .= $seed[$k];
        $new_acc_num = $rand;

        // Prepare file upload directory
        $uploadDir = '../../uploads/' . $email . '/';
        $img_path =  'uploads/' . $email . '/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        // Handle profile_pic file upload
        $profilePicPath = '';
        if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] == 0) {
            $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
            $maxSize = 2 * 1024 * 1024; // 2MB

            $fileTmp = $_FILES['profile_pic']['tmp_name'];
            $fileName = basename($_FILES['profile_pic']['name']);
            $fileType = mime_content_type($fileTmp);
            $fileSize = $_FILES['profile_pic']['size'];

            if (!in_array($fileType, $allowedTypes)) {
                echo 'Invalid image format. Only JPG, JPEG, PNG allowed.';
                exit;
            }

            if ($fileSize > $maxSize) {
                echo 'Image size should not exceed 2MB.';
                exit;
            }

            $newFileName = uniqid('profile_', true) . '.' . pathinfo($fileName, PATHINFO_EXTENSION);
            $profilePicPath = $img_path . $newFileName;
            $profilePicPath2 = $uploadDir . $newFileName;

            if (!move_uploaded_file($fileTmp, $profilePicPath2)) {
                echo 'Failed to upload profile picture.';
                exit;
            }
        }

        // Insert into users table
        $sql = "INSERT INTO users (firstname, account_num, lastname, middlename, nickname, email, phone, dob, zipcode, title, gender, address, country, state, city, ssn, usercurrency, account_type, password, reg_step, status, img_path)
                VALUES ('$firstname', '$new_acc_num', '$lastname', '$middlename', '$nickname', '$email', '$phone', '$dob', '$zipcode', '$title', '$gender', '$address', '$country', '$state', '$city', '$ssn', '$usercurrency', '$account_type', '$password', 'step5', 'active', '$profilePicPath')";

        if ($mysqli->query($sql) === TRUE) {
            $sqlCrypto = "INSERT INTO usercrypto (user) VALUES ('$email')";
            if ($mysqli->query($sqlCrypto) === TRUE) {
                $sqlCodes = "INSERT INTO code (user) VALUES ('$new_acc_num')";
                if ($mysqli->query($sqlCodes) === TRUE) {
                    echo 'success';
                    $_SESSION['inactive'] = $email;
                } else {
                    echo 'Error inserting into codes: ' . $mysqli->error;
                }
            } else {
                echo 'Error inserting into usercrypto: ' . $mysqli->error;
            }
        } else {
            echo 'Error inserting into users: ' . $mysqli->error;
        }
    } else {
        echo 'error_email_user_with_this_email_already_exists';
    }

    $mysqli->close();
}
?>
