<?php

namespace App\Controllers;

use App\Config\Database;
use App\Utils\Auth;
use App\Utils\Flash;
use PDO;

class RegisterController {

    public function index() {
        require_once __DIR__ . '/../../views/auth/register.php';
    }

    public function store() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header("Location: /register");
            exit;
        }

        $tenantName = $_POST['tenant_name'] ?? '';
        $adminName = $_POST['admin_name'] ?? '';
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';

        if (empty($tenantName) || empty($adminName) || empty($email) || empty($password)) {
            Flash::set('error', 'All fields are required.');
            header("Location: /register");
            exit;
        }

        // Remove auto-generated subdomain since it's dropped from DB.
        
        $db = Database::getInstance()->getConnection();

        try {
            $db->beginTransaction();

            // Create Tenant
            $stmt = $db->prepare("INSERT INTO tenants (name, email, status) VALUES (?, ?, 'inactive')");
            $stmt->execute([$tenantName, $email]);
            $tenantId = $db->lastInsertId();

            // Create Default Main Branch
            $stmt = $db->prepare("INSERT INTO branches (tenant_id, name) VALUES (?, 'Main Branch')");
            $stmt->execute([$tenantId]);
            $branchId = $db->lastInsertId();

            // Create Admin User
            $passwordHash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db->prepare("INSERT INTO users (tenant_id, branch_id, name, email, password_hash, role, status) VALUES (?, ?, ?, ?, ?, 'admin', 'inactive')");
            $stmt->execute([$tenantId, $branchId, $adminName, $email, $passwordHash]);
            $userId = $db->lastInsertId();

            $db->commit();

            Flash::set('success', 'Registration successful! Your account is pending Superadmin approval. You will be able to log in once activated.');
            header("Location: /login");
            exit;

        } catch (\PDOException $e) {
            $db->rollBack();
            Flash::set('error', "Registration failed. Email might already exist.");
            header("Location: /register");
            exit;
        }
    }
}
