<?php
session_start();
require_once __DIR__ . '/db.php';

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

function send_otp_sms(string $toPhone, string $otp, string &$error = ''): bool
{
    $sid = getenv('TWILIO_ACCOUNT_SID') ?: '';
    $token = getenv('TWILIO_AUTH_TOKEN') ?: '';
    $from = getenv('TWILIO_FROM_NUMBER') ?: '';

    if ($sid === '' || $token === '' || $from === '') {
        $error = 'SMS gateway is not configured. Set TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_FROM_NUMBER.';
        return false;
    }

    if (!function_exists('curl_init')) {
        $error = 'cURL is not enabled in PHP, so SMS could not be sent.';
        return false;
    }

    $url = "https://api.twilio.com/2010-04-01/Accounts/{$sid}/Messages.json";
    $payload = http_build_query([
        'From' => $from,
        'To' => $toPhone,
        'Body' => "Your OTP code is {$otp}"
    ]);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD => $sid . ':' . $token,
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_TIMEOUT => 20,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError !== '') {
        $error = "SMS send failed: {$curlError}";
        return false;
    }

    if ($httpCode < 200 || $httpCode >= 300) {
        $error = "SMS send failed with HTTP {$httpCode}.";
        return false;
    }

    return true;
}

// === FORM PROCESSING ===
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pending = [
        'company_name' => clean_input($_POST['company_name'] ?? ''),
        'email' => clean_input($_POST['email'] ?? ''),
        'phone_code' => clean_input($_POST['phone_code'] ?? '+91'),
        'phone' => clean_input($_POST['phone'] ?? ''),
        'password' => clean_input($_POST['password'] ?? ''),
        'country' => clean_input($_POST['country'] ?? ''),
        'state' => clean_input($_POST['state'] ?? ''),
        'terms' => isset($_POST['terms']) ? 1 : 0,
    ];

    $_SESSION['signup_pending_input'] = $pending;
    $_SESSION['signup_old_input'] = $pending;

    $field_errors = [];

    if ($pending['company_name'] === '') {
        $field_errors['company_name'] = "Please enter your organization name";
    }
    if (!filter_var($pending['email'], FILTER_VALIDATE_EMAIL)) {
        $field_errors['email'] = "Please enter your email";
    }
    if (!preg_match("/^[0-9]{10}$/", $pending['phone'])) {
        $field_errors['phone'] = "Please enter a valid mobile number";
    }
    if (strlen($pending['password']) < 8) {
        $field_errors['password'] = "Password cannot be less than 8 characters";
    }
    if ($pending['country'] === '') {
        $field_errors['country'] = "Please select your country";
    }
    if ($pending['state'] === '' || $pending['state'] === 'Select State') {
        $field_errors['state'] = "Please select your state";
    }
    if (empty($pending['terms'])) {
        $field_errors['terms'] = "Please read and accept the Terms of Service and Privacy Policy";
    }

    if (!empty($field_errors)) {
        $_SESSION['signup_field_errors'] = $field_errors;
        unset($_SESSION['signup_pending_input']);
        unset($_SESSION['signup_otp_code']);
        header("Location: signup.php");
        exit();
    }

    if (filter_var($pending['email'], FILTER_VALIDATE_EMAIL)) {
        $check_email = $conn->prepare("SELECT id FROM signup WHERE email = ?");
        if ($check_email === false) {
            $_SESSION['signup_field_errors'] = [
                'email' => 'Signup is unavailable because the signup table is missing or not ready in the database.'
            ];
            $_SESSION['signup_old_input'] = $pending;
            unset($_SESSION['signup_pending_input']);
            unset($_SESSION['signup_otp_code']);
            header("Location: signup.php");
            exit();
        }

        $check_email->bind_param("s", $pending['email']);
        $check_email->execute();
        $check_email->store_result();
        if ($check_email->num_rows > 0) {
            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'] = $pending;
            header("Location: signup.php");
            exit();
        }
    }

    $otp = (string)rand(100000, 999999);
    $_SESSION['signup_otp_code'] = $otp;

    $smsError = '';
    $toPhone = ($pending['phone_code'] ?? '') . ($pending['phone'] ?? '');
    $sent = send_otp_sms($toPhone, $otp, $smsError);

    if ($sent) {
        $_SESSION['otp_info'] = 'OTP sent to your mobile number.';
        unset($_SESSION['otp_error']);
    } else {
        $_SESSION['otp_error'] = $smsError;
        $_SESSION['otp_info'] = 'Dev OTP: ' . $otp;
    }

    header("Location: signup_otp.php");
    exit();
}

$pending = $_SESSION['signup_pending_input'] ?? null;
$otp_error = $_SESSION['otp_error'] ?? '';
$otp_info = $_SESSION['otp_info'] ?? '';
unset($_SESSION['otp_error']);
unset($_SESSION['otp_info']);

if (!$pending) {
    header("Location: signup.php");
    exit();
}

if (isset($_GET['resend']) && $_GET['resend'] === '1') {
    $otp = (string)rand(100000, 999999);
    $_SESSION['signup_otp_code'] = $otp;

    $smsError = '';
    $toPhone = ($pending['phone_code'] ?? '') . ($pending['phone'] ?? '');
    $sent = send_otp_sms($toPhone, $otp, $smsError);

    if ($sent) {
        $_SESSION['otp_info'] = 'OTP resent to your mobile number.';
        unset($_SESSION['otp_error']);
    } else {
        $_SESSION['otp_error'] = $smsError;
        $_SESSION['otp_info'] = 'Dev OTP: ' . $otp;
    }

    header('Location: signup_otp.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Verify OTP</title>
<link rel="stylesheet" href="signup.css">
<link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
</head>
<body class="otp-open">

<div class="otp-page-wrap">
    <iframe src="signup.php" class="otp-bg-frame" title="Signup background"></iframe>

    <div class="otp-overlay">
        <div class="otp-modal">
            <a href="signup.php" class="otp-close" aria-label="Close">&times;</a>
            <div class="otp-icon-wrap">
                <i class="fa-solid fa-mobile-screen-button otp-icon"></i>
            </div>
            <h3>PLEASE ENTER THE OTP</h3>
            <p>Enter the one-time password sent to your phone number.</p>
            <p class="otp-phone"><?php echo htmlspecialchars(($pending['phone_code'] ?? '') . ' ' . ($pending['phone'] ?? '')); ?> <a href="signup.php">Change</a></p>

            <form action="process_signup.php" method="POST">
                <input type="hidden" name="company_name" value="<?php echo htmlspecialchars($pending['company_name'] ?? ''); ?>">
                <input type="hidden" name="email" value="<?php echo htmlspecialchars($pending['email'] ?? ''); ?>">
                <input type="hidden" name="phone_code" value="<?php echo htmlspecialchars($pending['phone_code'] ?? '+91'); ?>">
                <input type="hidden" name="phone" value="<?php echo htmlspecialchars($pending['phone'] ?? ''); ?>">
                <input type="hidden" name="password" value="<?php echo htmlspecialchars($pending['password'] ?? ''); ?>">
                <input type="hidden" name="country" value="<?php echo htmlspecialchars($pending['country'] ?? ''); ?>">
                <input type="hidden" name="state" value="<?php echo htmlspecialchars($pending['state'] ?? ''); ?>">
                <?php if (!empty($pending['terms'])): ?>
                    <input type="hidden" name="terms" value="1">
                <?php endif; ?>

                <input type="text" name="otp" id="otpInput" class="otp-input" placeholder="Enter OTP" maxlength="6" required>
                <?php if (!empty($otp_error)): ?><p class="field-error"><?php echo htmlspecialchars($otp_error); ?></p><?php endif; ?>
                <?php if (!empty($otp_info)): ?><p class="otp-info"><?php echo htmlspecialchars($otp_info); ?></p><?php endif; ?>
                <p class="otp-resend">Didn't receive OTP? <a href="signup_otp.php?resend=1">Resend OTP</a></p>
                <button type="submit" class="otp-verify-btn">VERIFY</button>
            </form>
        </div>
    </div>
</div>

</body>
</html>
