<?php
session_start();
include('includes/dbconn.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $fullName = $_POST['fullname'];
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $companyName = $_POST['name'];
    $companyAddress = $_POST['address'];
    $companyMAddress = $_POST['maddress'];
    $companyIndustry = $_POST['industry'];

    $conn->begin_transaction();
    try {
        $sqlCompany = "INSERT INTO companies (name, industry, address, maddress) VALUES (?, ?, ?, ?)";
        $stmtCompany = $conn->prepare($sqlCompany);
        if (!$stmtCompany) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmtCompany->bind_param("ssss", $companyName, $companyIndustry, $companyAddress, $companyMAddress);
        if (!$stmtCompany->execute()) {
            throw new Exception("Execute failed: " . $stmtCompany->error);
        }
        $companyId = $conn->insert_id;

        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        $sqlUser = "INSERT INTO users (company_id, username, email, password_hash, full_name) VALUES (?, ?, ?, ?, ?)";
        $stmtUser = $conn->prepare($sqlUser);
        if (!$stmtUser) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmtUser->bind_param("issss", $companyId, $username, $email, $passwordHash, $fullName);
        if (!$stmtUser->execute()) {
            throw new Exception("Execute failed: " . $stmtUser->error);
        }

        // Insert into clients table
        $sqlClient = "INSERT INTO clients (client_name, email, company, start_date, company_id) VALUES (?, ?, ?, NOW(), ?)";
        $stmtClient = $conn->prepare($sqlClient);
        if (!$stmtClient) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $stmtClient->bind_param("sssi", $fullName, $email, $companyName, $companyId);
        if (!$stmtClient->execute()) {
            throw new Exception("Execute failed: " . $stmtClient->error);
        }

        $conn->commit();
        //echo "Registration successful. Company ID: " . $companyId;
        echo "Registration successful";
        header('Location: auth-login.php');
        exit();
    } catch (Exception $e) {
        $conn->rollback();
        echo "Error: " . $e->getMessage();
    }

    $stmtCompany->close();
    $stmtUser->close();
    $stmtClient->close(); // Close the client statement
    $conn->close();
}

?>
