<?php

session_start();

require_once __DIR__ . '/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: signup.php");
    exit();
}

// === INCLUDES ===
require_once 'includes/functions.php';

// === INPUT PROCESSING ===
$company   = clean_input($_POST['company_name'] ?? ''); 
$email     = clean_input($_POST['email'] ?? '');
$phone     = clean_input($_POST['phone'] ?? '');
$password  = clean_input($_POST['password'] ?? '');
$state     = clean_input($_POST['state'] ?? '');
$country   = clean_input($_POST['country'] ?? '');
$phoneCode = clean_input($_POST['phone_code'] ?? '+91');
$terms     = isset($_POST['terms']) ? 1 : 0;
$otp       = clean_input($_POST['otp'] ?? '');

$field_errors = [];

$old_input = [
    'company_name' => $company,
    'email' => $email,
    'phone' => $phone,
    'phone_code' => $phoneCode,
    'country' => $country ?: 'India',
    'state' => $state,
    'terms' => $terms
];

// === VALIDATION ===
if (empty($company)) {
    $field_errors['company_name'] = "Please enter your organization name";
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $field_errors['email'] = "Please enter your email";
}

if (!preg_match("/^[0-9]{10}$/", $phone)) {
    $field_errors['phone'] = "Please enter a valid mobile number";
}

if (strlen($password) < 8) {
    $field_errors['password'] = "Password cannot be less than 8 characters";
}

if (empty($state) || $state === "Select State") {
    $field_errors['state'] = "Please select your state";
}

if (empty($country)) {
    $field_errors['country'] = "Please select your country";
}

if (!$terms) {
    $field_errors['terms'] = "Please read and accept the Terms of Service and Privacy Policy";
}

if (!preg_match("/^[0-9]{6}$/", $otp)) {
    $_SESSION['otp_error'] = "Please enter a valid 6-digit OTP";
    $_SESSION['signup_pending_input'] = $old_input;
    header("Location: signup_otp.php");
    exit();
}

$expectedOtp = $_SESSION['signup_otp_code'] ?? '';
if ($expectedOtp === '' || $otp !== $expectedOtp) {
    $_SESSION['otp_error'] = "Invalid OTP. Please try again.";
    $_SESSION['signup_pending_input'] = $old_input;
    header("Location: signup_otp.php");
    exit();
}


/* CHECK ERRORS AND INSERT DATA */

if (count($field_errors) > 0) {
    $_SESSION['signup_field_errors'] = $field_errors;
    $_SESSION['signup_old_input'] = $old_input;
    unset($_SESSION['signup_pending_input']);
    header("Location: signup.php");
    exit();
} else {

    $password = password_hash($password, PASSWORD_DEFAULT);

// === DATABASE INSERT ===
$stmt = $conn->prepare("INSERT INTO signup(company_name, email, phone, password, state, country) VALUES(?,?,?,?,?,?)");

    if ($stmt === false) {
        $_SESSION['signup_errors'] = ["Signup is unavailable because the signup table is missing or not ready in the database."];
        header("Location: signup.php");
        exit();
    }

    $stmt->bind_param("ssssss", $company, $email, $phone, $password, $state, $country);

    if ($stmt->execute()) {
        $signupId = (int) $stmt->insert_id;
        $orgId = payroll_generate_org_code($signupId);
        $update = $conn->prepare("UPDATE signup SET org_id = ? WHERE id = ?");
        if ($update !== false) {
            $update->bind_param("si", $orgId, $signupId);
            $update->execute();
            $update->close();
        }

        $_SESSION['signup_success'] = "Signup successful.";
        $_SESSION['user_company'] = $company;
        $_SESSION['user_email'] = $email;
        $_SESSION['user'] = $email;
        unset($_SESSION['signup_pending_input']);
        unset($_SESSION['signup_otp_code']);
        header("Location: organization.php");
        exit();
    } else {
        if ((int)$stmt->errno === 1062) {
            unset($_SESSION['signup_pending_input']);
            unset($_SESSION['signup_otp_code']);
            $_SESSION['signup_field_errors'] = [
                'email' => "An account already exists for this email address. <a href='signin.php'>Sign in</a> or use a different email address to sign up."
            ];
            $_SESSION['signup_old_input'] = $old_input;
            header("Location: signup.php");
            exit();
        }
        $_SESSION['signup_errors'] = ["Error saving data"];
        header("Location: signup.php");
        exit();
    }
}

?>
