<?php
session_start();

require("../includes/db_connect.php");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ssn']) && isset($_POST['legal_name']) && isset($_POST['nationality']) && isset($_POST['date_of_birth']) && isset($_POST['address']) && isset($_POST['mobile_number']) && isset($_POST['email'])) {

    $legal_name = $_POST['legal_name'];
    $nationality = $_POST['nationality'];
    $date_of_birth = $_POST['date_of_birth'];
    $address = $_POST['address'];
    $mobile_number = $_POST['mobile_number'];
    $email = $_POST['email'];
    $ssn = $_POST['ssn'];

    $accountId = $_SESSION['usr_accountId'];

    $sql = "SELECT * FROM users WHERE accountId = :accountId LIMIT 1";
    $sth = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
    $sth->execute([':accountId' => $accountId]);
    $users = $sth->fetchAll();

    foreach ($users as $key => $value) {
        $country = $value['country'];

         if ($country == "United States of America") {

            if (is_numeric($ssn)) {

                if (strlen($ssn) != 9) {
                    die("Enter a valid SSN.");
                } 

            }else {
                die("Enter a valid SSN.");
            }

        }else {
            $ssn = "";
        }
    }

    $identity_file = $_FILES["identity_file"]["name"];
    $backside_file = $_FILES["backside_file"]["name"];


    $identity_file_name = "identity_documents/" . $_SESSION['usr_accountId'] . "_" . basename($identity_file);
    $backside_file_name = "identity_documents/" . $_SESSION['usr_accountId'] . "_" . basename($backside_file);

    $target1 = "../" . $identity_file_name;
    $target2 = "../" . $backside_file_name;
    
    $tmp_file1 = $_FILES["identity_file"]["tmp_name"];
    $tmp_file2 = $_FILES["backside_file"]["tmp_name"];
    
    if (getimagesize($tmp_file1) === false && getimagesize($tmp_file2) === false) {
        die('The provided file is not a valid image.');
    }

    if (move_uploaded_file($tmp_file1, $target1) && move_uploaded_file($tmp_file2, $target2)) {

        $kyc_usr_sql = "SELECT * FROM kyc_documents WHERE accountId =? LIMIT 1";
        $kyc_usr_sth = $conn->prepare($kyc_usr_sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
        $kyc_usr_sth->execute([$accountId]);
        $kyc_users = $kyc_usr_sth->fetchAll();

        if (count($kyc_users) > 0) {
            
            $identity_sql = "UPDATE kyc_documents SET full_legal_name=?, ssn=?, nationality=?, date_of_birth=?, address=?, mobile_number=?, email_address=?, front_document=?, back_document=?, selfie_document=? WHERE accountId=?";

            $create_kyc = $conn->prepare($identity_sql)->execute([$legal_name, "$ssn", $nationality, $date_of_birth, $address, $mobile_number, $email, $identity_file_name, $backside_file_name, "default", $_SESSION['usr_accountId']]);

            if ($create_kyc) {
                $profile_sql = "UPDATE users SET verification_identity=? WHERE accountId=?";
			    $update_profile = $conn->prepare($profile_sql)->execute([1, $accountId]);
                die("success");
            } else {
                die('An unexpected error occurred. Please try again.');
            }
        } else {

            $user_sql = "INSERT INTO kyc_documents (accountId, full_legal_name, ssn, nationality, date_of_birth, address, mobile_number, email_address, front_document, back_document, selfie_document) VALUES (?,?,?,?,?,?,?,?,?,?,?)";

            $create_user = $conn->prepare($user_sql)->execute([$accountId, "default", "default", "default", "default", "default", "default", "default", "default", "default", "default"]);

            if ($create_user) {

                $identity_sql = "UPDATE kyc_documents SET full_legal_name=?, ssn=?, nationality=?, date_of_birth=?, address=?, mobile_number=?, email_address=?, front_document=?, back_document=?, selfie_document=? WHERE accountId=?";

                $create_kyc = $conn->prepare($identity_sql)->execute([$legal_name, "$ssn", $nationality, $date_of_birth, $address, $mobile_number, $email, $identity_file_name, $backside_file_name, "default", $_SESSION['usr_accountId']]);

                if ($create_kyc) {
                    $profile_sql = "UPDATE users SET verification_identity=? WHERE accountId=?";
                    $update_profile = $conn->prepare($profile_sql)->execute([1, $accountId]);
                    die("success");
                } else {
                    die('An unexpected error occurred. Please try again.');
                }
            } else {
                die('An unexpected error occurred. Please try again.');
            }
        }
    } else {
        die("An unexpected error occurred.");
    }
} else {
    die('Invalid request.');
}