<?php
header("Content-Type: application/json");

require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

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

// í ½í´¹ Capture raw input
$rawInput = file_get_contents("php://input");
//file_put_contents("log.txt", $rawInput . PHP_EOL, FILE_APPEND);

$data = json_decode($rawInput, true);

// í ½í´¹ Fallback: if not JSON, check $_POST
if (!$data) {
    $data = $_POST;
}

// í ½í´¹ Ensure we got something
if (!$data) {
    echo json_encode(["status" => "error", "message" => "No valid input received"]);
    exit;
}else{

if(isset($data["signupType"])){
	
// í ½í´¹ Handle signup

  $accountType = isset($data["signupType"]) ? trim($data["signupType"]) : "Personal-signup";

if($accountType=='Personal-signup'){
	
personalsignup($data);

}
if($accountType=='Business-signup'){
	
companysignup($data);

}
}
	
}
$email="";

function personalsignup($data) {
try{
	
	require('dbcon.php');
        // í ½í´¹ Collect fields
        $firstname   = isset($data["firstname"]) ? trim($data["firstname"]) : "";
        $phone       = isset($data["phone"]) ? trim($data["phone"]) : "";
        $email       = isset($data["email"]) ? trim($data["email"]) : "";
        $passwordVal = isset($data["password"]) ? trim($data["password"]) : "";
        $accountType = isset($data["signupType"]) ? trim($data["signupType"]) : "Personal-signup";

        // í ½í´¹ Validate required fields
        if (empty($firstname) || empty($phone) || empty($email) || empty($passwordVal)) {
            echo json_encode(["status" => "error", "message" => "All fields are required"]);
            exit;
        }

        $date = date('Y-m-d H:i:s');
        $verificationCode = rand(10000000, 99999999);
        $passwordHash = md5($passwordVal);

        // í ½í´¹ Check if user exists
        $user_check = $pdo->prepare("SELECT id FROM users WHERE email = :email");
        $user_check->execute([":email" => $email]);
        
        if ($user_check->rowCount() > 0) {
            echo json_encode(["status" => "failed", "message" => "Email Already Exist"]);
            exit;
        }
			//========================================================
			//GENERATING A RANDON NUMBER FOR ACCOUNT NUMBER
			//========================================================
			
			function checkacc(){
			require('dbcon.php');
				$acc_no1='7'.mt_rand(10000,99999).mt_rand(1000,9999);
			$sql_ac=$pdo->prepare("select *from users where account_no='$acc_no1'");
			$sql_ac->execute();
			
			$num_sql_ac=$sql_ac->rowCount();
			if($num_sql_ac>0){
				//wiv code already exist rerun function
				checkacc();
			}
			else{
				//wiv code generated dont exist
				$ac_no=$acc_no1;
				return $ac_no;
			}
			}
			$acc_no=checkacc();
			
file_put_contents("log.txt", $acc_no . PHP_EOL, FILE_APPEND);

        // í ½í´¹ Insert new user
        $stmt = $pdo->prepare("INSERT INTO users (name, phone, email, password, type, verificationcode, date, account_no) 
                               VALUES (:firstname, :phone, :email, :password, :accountType, :verificationcode, :date,:account_no)");
        $stmt->execute([
            ":firstname" => ucwords($firstname),
            ":phone" => $phone,
            ":email" => $email,
            ":password" => $passwordHash,
            ":account_no" => $acc_no,
            ":accountType" => $accountType,
            ":verificationcode" => $verificationCode,
            ":date" => $date,
        ]);

        echo json_encode(["status" => "success", "message" => "User registered successfully"]);

    } catch (PDOException $e) {
        // Log error (optional)
        file_put_contents("log.txt", "DB ERROR: " . $e->getMessage() . PHP_EOL, FILE_APPEND);

        echo json_encode([
            "status" => "error",
            "message" => "Database error: " . $e->getMessage()
        ]);
        exit;
    }
}

function companysignup($data) {
try{
	require('dbcon.php');
        // í ½í´¹ Collect fields
        $firstname   = isset($data["firstname"]) ? trim($data["firstname"]) : "";
        $phone       = isset($data["phone"]) ? trim($data["phone"]) : "";
        $email       = isset($data["email"]) ? trim($data["email"]) : "";
        $passwordVal = isset($data["password"]) ? trim($data["password"]) : "";
        $accountType = isset($data["signupType"]) ? trim($data["signupType"]) : "Personal-signup";

        // í ½í´¹ Validate required fields
        if (empty($firstname) || empty($phone) || empty($email) || empty($passwordVal)) {
            echo json_encode(["status" => "error", "message" => "All fields are required"]);
            exit;
        }

        $date = date('Y-m-d H:i:s');
        $verificationCode = rand(10000000, 99999999);
        $passwordHash = password_hash($passwordVal, PASSWORD_BCRYPT);

        // í ½í´¹ Check if user exists
        $user_check = $pdo->prepare("SELECT id FROM users WHERE email = :email");
        $user_check->execute([":email" => $email]);
        
        if ($user_check->rowCount() > 0) {
            echo json_encode(["status" => "failed", "message" => "Email Already Exist"]);
            exit;
        }

        // í ½í´¹ Insert new user
        $stmt = $pdo->prepare("INSERT INTO users (name, phone, email, password, type, verificationcode, date) 
                               VALUES (:firstname, :phone, :email, :password, :accountType, :verificationcode, :date)");
        $stmt->execute([
            ":firstname" => ucwords($firstname),
            ":phone" => $phone,
            ":email" => $email,
            ":password" => $passwordHash,
            ":accountType" => $accountType,
            ":verificationcode" => $verificationCode,
            ":date" => $date,
        ]);

        echo json_encode(["status" => "success", "message" => "User registered successfully"]);

    } catch (PDOException $e) {
        // Log error (optional)
        file_put_contents("log.txt", "DB ERROR: " . $e->getMessage() . PHP_EOL, FILE_APPEND);

        echo json_encode([
            "status" => "error",
            "message" => "Database error: " . $e->getMessage()
        ]);
        exit;
    }
}

?>
