<?php
require_once '../includes/config.php';
require_once 'smtp_mail.php';
require_once 'helpers.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $company_name = trim($_POST['company_name'] ?? '');
    $name         = trim($_POST['name'] ?? '');
    $email        = trim($_POST['email'] ?? '');
    $password     = $_POST['password'] ?? '';
    $confirm      = $_POST['confirm_password'] ?? '';
    $role         = $_POST['role'] ?? 'admin'; // first user is usually admin

    /* ---------------------------
       Basic validation
    --------------------------- */
    if ($company_name === '' || $name === '' || $email === '') {
        die("<script>alert('All fields are required');history.back();</script>");
    }

    if ($password !== $confirm) {
        die("<script>alert('Passwords do not match');history.back();</script>");
    }

    /* ---------------------------
       Check email uniqueness
    --------------------------- */
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {

                jsAlert(
            'Email already Exist',
            'You have an account with this email. Reach out to our support team',
            'error',
            '../sign-in.php'
        );
    }
    $stmt->close();

    /* ---------------------------
       Prepare OTP
    --------------------------- */
    $otp         = rand(100000, 999999);
    $otp_expiry  = date("Y-m-d H:i:s", strtotime("+10 minutes"));
    $hashedPass  = password_hash($password, PASSWORD_DEFAULT);

    /* ---------------------------
       START TRANSACTION
    --------------------------- */
    $conn->begin_transaction();

    try {

        /* ---------------------------
           1️⃣ Insert company
        --------------------------- */
        $stmt = $conn->prepare("
            INSERT INTO company (company_name,company_email)
            VALUES (?,?)
        ");
        $stmt->bind_param("ss", $company_name,$email);
        $stmt->execute();

        $company_id = $conn->insert_id; // 🔑 VERY IMPORTANT
        $stmt->close();

        /* ---------------------------
           2️⃣ Insert user (linked)
        --------------------------- */
        $stmt = $conn->prepare("
            INSERT INTO users 
            (company_id, name, email, password, role, email_otp, otp_expires)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->bind_param(
            "issssss",
            $company_id,
            $name,
            $email,
            $hashedPass,
            $role,
            $otp,
            $otp_expiry
        );

        $stmt->execute();
        $stmt->close();

        /* ---------------------------
           COMMIT
        --------------------------- */
        $conn->commit();

        /* ---------------------------
           Send OTP
        --------------------------- */
        sendOTPEmail($email, $name, $otp);

        header("Location: verify-email.php?email=" . urlencode($email));
        exit;

    } catch (Exception $e) {

        /* ---------------------------
           ROLLBACK ON ERROR
        --------------------------- */
        $conn->rollback();
        die("<script>alert('Registration FAILED. Try again!');history.back();</script>");
    }
}
?>
