<?php
require_once __DIR__ . '/../config/theconfig.php'; 

header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}


ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);


$firstName = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastName = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$country = filter_input(INPUT_POST, 'country', FILTER_SANITIZE_STRING);
$state = filter_input(INPUT_POST, 'state', FILTER_SANITIZE_STRING);
$dob = filter_input(INPUT_POST, 'dob', FILTER_SANITIZE_STRING);
$gender = filter_input(INPUT_POST, 'gender', FILTER_SANITIZE_STRING);
$city = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_STRING);
$loginId = filter_input(INPUT_POST, 'loginId', FILTER_SANITIZE_STRING);
$loginPassword = $_POST['loginPassword'];
$confirmPassword = $_POST['confirmPassword'];
$transactionPassword = $_POST['transactionPassword'];
$bankBranch = filter_input(INPUT_POST, 'bankBranch', FILTER_SANITIZE_STRING);
$accountType = filter_input(INPUT_POST, 'accountType', FILTER_SANITIZE_STRING);

$errors = [];
if (!preg_match("/^[a-zA-Z\s]+$/", $firstName)) {
    $errors[] = "First name must contain only letters and spaces.";
}
if (!preg_match("/^[a-zA-Z\s]+$/", $lastName)) {
    $errors[] = "Last name must contain only letters and spaces.";
}
if (!preg_match("/^[0-9]{10,15}$/", $phone)) {
    $errors[] = "Phone number must be 10-15 digits.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email format.";
}
if ($loginPassword !== $confirmPassword) {
    $errors[] = "Passwords do not match.";
}
if (strlen($loginPassword) < 8) {
    $errors[] = "Password must be at least 8 characters long.";
}
if (empty($country) || empty($state) || empty($city) || empty($gender) || empty($dob) || empty($bankBranch) || empty($accountType)) {
    $errors[] = "All fields are required.";
}

// Check for duplicate loginId or email
$stmt = $conn->prepare("SELECT COUNT(*) FROM customers WHERE loginid = ? OR email = ?");
$stmt->bind_param("ss", $loginId, $email);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
if ($count > 0) {
    $errors[] = "Login ID or email already exists.";
}

if (!empty($errors)) {
    echo json_encode(['status' => 'error', 'message' => implode(" ", $errors)]);
    exit;
}

// Generate account-related info
$customerid = 'CUST' . rand(100000, 999999);
$accountno = 'SB' . rand(10000000, 99999999);
$accstatus = 'Pending';
$accopendate = date('Y-m-d');
$ifsccode = 'SBIN0001234';
$activationcode = rand(100000, 999999);
$cot = rand(100000, 999999);
$imf = rand(100000, 999999);
$taxcode = rand(100000, 999999);
$image = 'default.png';
$lastlogin = '';
$transfer_count = 0;
$regstatus = 'visible';
$card_long_digit = '';
$valid_thru = '';
$otp = '';
$otp_attempts = 0;
$otp_generated_at = '';

$accpassword = $loginPassword;
$transpassword = $transactionPassword;


$sql = "INSERT INTO customers (accountno, acctype, ifsccode, firstname, lastname, email, phone, loginid,
        accpassword, transpassword, cot, imf, accstatus, city, state, country, accopendate,
        lastlogin, image, dob, gender, activationcode, taxcode, transfer_count, regstatus,
        card_long_digit, valid_thru, otp, otp_attempts, otp_generated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $conn->error]);
    exit;
}

$stmt->bind_param(
    "ssssssssssssssssssssssissssiii",
    $accountno, $accountType, $ifsccode, $firstName, $lastName, $email, $phone, $loginId,
    $accpassword, $transpassword, $cot, $imf, $accstatus, $city, $state, $country, $accopendate,
    $lastlogin, $image, $dob, $gender, $activationcode, $taxcode, $transfer_count, $regstatus,
    $card_long_digit, $valid_thru, $otp, $otp_attempts, $otp_generated_at
);


if ($stmt->execute()) {
    $customerid = $conn->insert_id;

    $accountbalance = 0; 
    $sql_accounts = "INSERT INTO accounts (accno, customerid, accstatus, accopendate, accounttype, accountbalance) 
                     VALUES (?, ?, ?, ?, ?, ?)";
    $stmt_accounts = $conn->prepare($sql_accounts);
    if (!$stmt_accounts) {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $conn->error]);
        $stmt->close();
        $conn->close();
        exit;
    }

    $stmt_accounts->bind_param(
        "sssssd",
        $accountno, 
        $customerid, 
        $accstatus,
        $accopendate,
        $accountType,
        $accountbalance 
    );

    if (!$stmt_accounts->execute()) {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $stmt_accounts->error]);
        $stmt_accounts->close();
        $stmt->close();
        $conn->close();
        exit;
    }
    $stmt_accounts->close();

    echo json_encode(['status' => 'success']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $stmt->error]);
}
$stmt->close();
$conn->close();
?>