<?php
class BranchController extends Controller
{
    // ── List branches ────────────────────────────────────────
    public function index(): void
    {
        Auth::requirePermission('branches.manage');

        $branches = Database::fetchAll(
            "SELECT b.*,
                    COUNT(u.id) AS user_count
             FROM branches b
             LEFT JOIN users u ON u.branch_id = b.id AND u.status = 'active'
             GROUP BY b.id
             ORDER BY b.is_main DESC, b.name ASC"
        );

        $pageTitle  = 'Branch Management';
        $breadcrumb = [['label' => 'Admin'], ['label' => 'Branches']];
        ob_start();
        require APP_PATH . '/views/branches/index.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/main.php';
    }

    // ── Create form ──────────────────────────────────────────
    public function create(): void
    {
        Auth::requirePermission('branches.manage');
        $branch     = null;
        $pageTitle  = 'Add Branch';
        $breadcrumb = [
            ['label' => 'Branches', 'url' => APP_URL . '/branches'],
            ['label' => 'Add Branch'],
        ];
        ob_start();
        require APP_PATH . '/views/branches/form.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/main.php';
    }

    // ── Store new branch ─────────────────────────────────────
    public function store(): void
    {
        Auth::requirePermission('branches.manage');
        Auth::requireCsrf();

        $name    = trim(Security::strip($this->post('name', '')));
        $address = trim(Security::strip($this->post('address', '')));
        $phone   = trim(Security::strip($this->post('phone', '')));
        $email   = trim(Security::email($this->post('email', '')));
        $isMain  = (int)$this->post('is_main', 0);

        if (!$name) {
            redirectWith(APP_URL . '/branches/create', 'error', 'Branch name is required.');
            return;
        }

        // Only one main branch
        if ($isMain) {
            Database::execute('UPDATE branches SET is_main = 0');
        }

        Database::execute(
            'INSERT INTO branches (name, address, phone, email, is_main, status)
             VALUES (?, ?, ?, ?, ?, ?)',
            [$name, $address ?: null, $phone ?: null, $email ?: null, $isMain, 'active']
        );

        Auth::logAudit(Auth::id(), 'branch_create', 'branches', "Created branch: {$name}");
        redirectWith(APP_URL . '/branches', 'success', "Branch \"{$name}\" created.");
    }

    // ── Edit form ────────────────────────────────────────────
    public function edit(string $id): void
    {
        Auth::requirePermission('branches.manage');

        $branch = Database::fetchOne('SELECT * FROM branches WHERE id = ?', [(int)$id]);
        if (!$branch) {
            redirectWith(APP_URL . '/branches', 'error', 'Branch not found.');
            return;
        }

        // Users in this branch
        $branchUsers = Database::fetchAll(
            "SELECT u.id, u.name, u.username, r.role_name
             FROM users u JOIN roles r ON r.id = u.role_id
             WHERE u.branch_id = ? AND u.status = 'active'
             ORDER BY u.name", [(int)$id]
        );

        $pageTitle  = 'Edit Branch: ' . $branch['name'];
        $breadcrumb = [
            ['label' => 'Branches', 'url' => APP_URL . '/branches'],
            ['label' => 'Edit'],
        ];
        ob_start();
        require APP_PATH . '/views/branches/form.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/main.php';
    }

    // ── Update branch ────────────────────────────────────────
    public function update(string $id): void
    {
        Auth::requirePermission('branches.manage');
        Auth::requireCsrf();

        $branchId = (int)$id;
        $branch   = Database::fetchOne('SELECT * FROM branches WHERE id = ?', [$branchId]);
        if (!$branch) {
            redirectWith(APP_URL . '/branches', 'error', 'Branch not found.');
            return;
        }

        $name    = trim(Security::strip($this->post('name', '')));
        $address = trim(Security::strip($this->post('address', '')));
        $phone   = trim(Security::strip($this->post('phone', '')));
        $email   = trim(Security::email($this->post('email', '')));
        $isMain  = (int)$this->post('is_main', 0);
        $status  = Security::enum($this->post('status', 'active'), ['active','inactive'], 'active');

        if (!$name) {
            redirectWith(APP_URL . '/branches/edit/' . $branchId, 'error', 'Branch name required.');
            return;
        }

        // Cannot deactivate main branch
        if ($branch['is_main'] && $status === 'inactive') {
            redirectWith(APP_URL . '/branches/edit/' . $branchId, 'error', 'Cannot deactivate the main branch.');
            return;
        }

        // Only one main branch
        if ($isMain && !$branch['is_main']) {
            Database::execute('UPDATE branches SET is_main = 0 WHERE id != ?', [$branchId]);
        }

        Database::execute(
            'UPDATE branches SET name=?, address=?, phone=?, email=?, is_main=?, status=? WHERE id=?',
            [$name, $address ?: null, $phone ?: null, $email ?: null, $isMain, $status, $branchId]
        );

        Auth::logAudit(Auth::id(), 'branch_update', 'branches', "Updated branch: {$name}");
        redirectWith(APP_URL . '/branches', 'success', "Branch \"{$name}\" updated.");
    }

    // ── Delete branch ────────────────────────────────────────
    public function delete(string $id): void
    {
        Auth::requirePermission('branches.manage');
        Auth::requireCsrf();

        $branchId = (int)$id;
        $branch   = Database::fetchOne('SELECT * FROM branches WHERE id = ?', [$branchId]);

        if (!$branch) {
            redirectWith(APP_URL . '/branches', 'error', 'Branch not found.');
            return;
        }
        if ($branch['is_main']) {
            redirectWith(APP_URL . '/branches', 'error', 'Cannot delete the main branch.');
            return;
        }

        $userCount = (int) Database::fetchColumn(
            'SELECT COUNT(*) FROM users WHERE branch_id = ?', [$branchId]
        );
        if ($userCount > 0) {
            redirectWith(APP_URL . '/branches', 'error',
                "Cannot delete — {$userCount} user(s) assigned. Reassign them first.");
            return;
        }

        Database::execute('DELETE FROM branches WHERE id = ?', [$branchId]);
        Auth::logAudit(Auth::id(), 'branch_delete', 'branches', "Deleted branch: {$branch['name']}");
        redirectWith(APP_URL . '/branches', 'success', "Branch \"{$branch['name']}\" deleted.");
    }

    // ── Assign user to branch ────────────────────────────────
    public function assignUser(): void
    {
        Auth::requirePermission('branches.manage');
        Auth::requireCsrf();

        $userId   = (int)$this->post('user_id', 0);
        $branchId = (int)$this->post('branch_id', 0);

        $user   = Database::fetchOne('SELECT id, name FROM users WHERE id = ?', [$userId]);
        $branch = Database::fetchOne('SELECT id, name FROM branches WHERE id = ?', [$branchId]);

        if (!$user || !$branch) {
            redirectWith(APP_URL . '/branches', 'error', 'Invalid user or branch.');
            return;
        }

        Database::execute('UPDATE users SET branch_id = ? WHERE id = ?', [$branchId, $userId]);
        Auth::logAudit(Auth::id(), 'user_branch_assign', 'branches',
            "Assigned {$user['name']} to branch {$branch['name']}");

        redirectWith(APP_URL . '/branches/edit/' . $branchId, 'success',
            "{$user['name']} assigned to {$branch['name']}.");
    }

    // ── Assign all unassigned users to a branch ──────────────
    public function assignAll(): void
    {
        Auth::requirePermission('branches.manage');
        Auth::requireCsrf();

        $branchId = (int)$this->post('branch_id', 1);
        $branch   = Database::fetchOne('SELECT * FROM branches WHERE id = ?', [$branchId]);
        if (!$branch) {
            redirectWith(APP_URL . '/branches', 'error', 'Branch not found.');
            return;
        }

        $count = Database::execute(
            'UPDATE users SET branch_id = ? WHERE branch_id IS NULL',
            [$branchId]
        );

        redirectWith(APP_URL . '/branches/edit/' . $branchId, 'success',
            "{$count} unassigned user(s) moved to \"{$branch['name']}\".");
    }
}