<?php
session_start();

require_once __DIR__ . '/../db/db.php';
require_once __DIR__ . '/../includes/functions.php';

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

$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'] ?? '');

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

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/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/signup_otp.php');
    exit();
}

$field_errors = [];
if ($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 ($state === '' || $state === 'Select State') $field_errors['state'] = 'Please select your state';
if ($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 ($field_errors) {
    $_SESSION['signup_field_errors'] = $field_errors;
    $_SESSION['signup_old_input'] = $old_input;
    unset($_SESSION['signup_pending_input']);
    header('Location: ../signup/signup.php');
    exit();
}

$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$emptyOrgId = '';

$stmt = $conn->prepare('INSERT INTO signup (company_name, email, phone, phone_code, password, state, country, org_id) 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/signup.php');
    exit();
}

$stmt->bind_param('ssssssss', $company, $email, $phone, $phoneCode, $passwordHash, $state, $country, $emptyOrgId);

if (!$stmt->execute()) {
    if ((int) $stmt->errno === 1062) {
        unset($_SESSION['signup_pending_input'], $_SESSION['signup_otp_code']);
        $_SESSION['signup_field_errors'] = [
            'email' => "An account already exists for this email address. <a href='../signin/signin.php'>Sign in</a> or use a different email address to sign up."
        ];
        $_SESSION['signup_old_input'] = $old_input;
        header('Location: ../signup/signup.php');
        exit();
    }

    $_SESSION['signup_errors'] = ['Error saving data'];
    header('Location: ../signup/signup.php');
    exit();
}

$signupId = (int) $stmt->insert_id;
$orgId = payroll_generate_org_code($signupId);
$stmt->close();

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

$userStmt = $conn->prepare('INSERT INTO users (business_name, email, password_hash, phone_country_code, phone_number, is_phone_verified) VALUES (?, ?, ?, ?, ?, 1)');
if ($userStmt !== false) {
    $userStmt->bind_param('sssss', $company, $email, $passwordHash, $phoneCode, $phone);
    $userStmt->execute();
    $_SESSION['user_id'] = (int) $userStmt->insert_id;
    $userStmt->close();
}

$_SESSION['signup_success'] = 'Signup successful.';
$_SESSION['user_company'] = $company;
$_SESSION['user_email'] = $email;
$_SESSION['verified_signup'] = [
    'business_name' => $company,
    'email' => $email,
    'phone_code' => $phoneCode,
    'phone' => $phone,
    'country' => $country,
    'state' => $state,
    'terms' => $terms,
    'user_id' => $_SESSION['user_id'] ?? null,
];
$_SESSION['authenticated'] = true;
unset($_SESSION['signup_pending_input'], $_SESSION['signup_otp_code']);
header('Location: ../organization/organization.php');
exit();












