<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

include("../includes/db_connection.php");

/* PHPMailer */
require '../includes/PHPMailer/src/PHPMailer.php';
require '../includes/PHPMailer/src/SMTP.php';
require '../includes/PHPMailer/src/Exception.php';

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

if($_SERVER["REQUEST_METHOD"]=="POST"){

$name = $_POST['name'];
$org_name = $_POST['org_name'];
$tax_id = $_POST['tax_id'];
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$phone = $_POST['phone'];
$address = $_POST['address'];
$country = $_POST['country'];
$pin_zip = $_POST['pin_zip'];

$status = "under_review";
$email_verified = 0;

$otp = rand(100000,999999);
$otp_expiry = date("Y-m-d H:i:s", strtotime("+10 minutes"));

/* ===== Upload Document ===== */

$upload_dir = "../upload/";

if(!is_dir($upload_dir)){
mkdir($upload_dir,0777,true);
}

$legal_document = "";

if(isset($_FILES['legal_document']) && $_FILES['legal_document']['error']==0){

$ext = pathinfo($_FILES['legal_document']['name'], PATHINFO_EXTENSION);

if(strtolower($ext)!="pdf"){
die("Only PDF file allowed");
}

$legal_document = time().rand(1000,9999).".pdf";

move_uploaded_file(
$_FILES['legal_document']['tmp_name'],
$upload_dir.$legal_document
);

}

/* ===== Check Duplicate Email ===== */

$check = $conn->prepare("SELECT id FROM associates WHERE email=?");
$check->bind_param("s",$email);
$check->execute();
$check->store_result();

if($check->num_rows > 0){
die("Email already registered.");
}

/* ===== Insert Data ===== */

$stmt = $conn->prepare("INSERT INTO associates
(name,org_name,tax_id,email,password,phone,address,country,pin_zip,legal_document,otp_code
,otp_expiry,status,email_verified)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

$stmt->bind_param("sssssssssssssi",
$name,$org_name,$tax_id,$email,$password,
$phone,$address,$country,$pin_zip,
$legal_document,$otp,$otp_expiry,$status,$email_verified
);

if(!$stmt->execute()){
die("Database Error: ".$stmt->error);
}

/* ===== Send OTP Email ===== */

$mail = new PHPMailer(true);

try{

$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'merautube@gmail.com';
$mail->Password = 'gsxcbesejondrwuy';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('merautube@gmail.com','ACME Certification');
$mail->addAddress($email,$name);

$mail->isHTML(true);
$mail->Subject = "OTP Verification";

$mail->Body = "
<h3>Hello $name,</h3>
<p>Your OTP for registration verification is:</p>
<h2>$otp</h2>
<p>This OTP will expire in 10 minutes.</p>
";

$mail->send();

}catch(Exception $e){
die("Mail Error: ".$mail->ErrorInfo);
}

/* ===== Redirect to OTP Page ===== */

header("Location: verify_otp.php?email=".$email);
exit;

}
?>