<?php
/**
 * SalonPro X - Branch Management Controller
 */

namespace Modules\Branches\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Session;
use core\View;

class BranchController extends Controller
{
    /**
     * List all branches
     */
    public function index(): void
    {
        Auth::requirePermission('branches_view');

        $db = Database::getInstance();
        $branches = $db->table('branches')
            ->select('branches.*, (SELECT COUNT(*) FROM users WHERE branch_id = branches.id) as user_count')
            ->orderBy('name', 'ASC')
            ->get();

        $this->view('Branches/index', [
            'title' => 'Branches',
            'branches' => $branches,
            'breadcrumb' => ['Branches' => url('branches')],
        ]);
    }

    /**
     * Show create form
     */
    public function create(): void
    {
        Auth::requirePermission('branches_create');
        $this->view('Branches/create', [
            'title' => 'Add Branch',
            'breadcrumb' => ['Branches' => url('branches'), 'Add' => url('branches/create')],
        ]);
    }

    /**
     * Store new branch
     */
    public function store(): void
    {
        Auth::requirePermission('branches_create');

        $data = $this->validate([
            'name' => 'required|max_length:100',
            'phone' => 'max_length:20',
            'email' => 'email|max_length:100',
            'city' => 'max_length:100',
            'state' => 'max_length:100',
            'zip' => 'max_length:20',
            'tax_id' => 'max_length:50',
        ]);

        $db = Database::getInstance();
        $data['slug'] = strtolower(str_replace(' ', '-', $data['name']));

        $db->table('branches')->insert($data);
        Auth::logActivity('branch_create', 'Created branch: ' . $data['name']);
        Session::setAlert('success', 'Branch created successfully.');
        $this->redirect(url('branches'));
    }

    /**
     * Show edit form
     */
    public function edit(int $id): void
    {
        Auth::requirePermission('branches_edit');

        $db = Database::getInstance();
        $branch = $db->table('branches')->find($id);

        if (!$branch) {
            Session::setAlert('danger', 'Branch not found.');
            $this->redirect(url('branches'));
            return;
        }

        $this->view('Branches/edit', [
            'title' => 'Edit Branch',
            'branch' => $branch,
            'breadcrumb' => ['Branches' => url('branches'), 'Edit' => url('branches/edit/' . $id)],
        ]);
    }

    /**
     * Update branch
     */
    public function update(int $id): void
    {
        Auth::requirePermission('branches_edit');

        $data = $this->validate([
            'name' => 'required|max_length:100',
            'phone' => 'max_length:20',
            'email' => 'email|max_length:100',
            'city' => 'max_length:100',
            'state' => 'max_length:100',
            'zip' => 'max_length:20',
            'tax_id' => 'max_length:50',
            'status' => 'in:active,inactive',
        ]);

        $db = Database::getInstance();
        $data['slug'] = strtolower(str_replace(' ', '-', $data['name']));

        $db->table('branches')->where('id', $id)->update($data);
        Auth::logActivity('branch_update', 'Updated branch: ' . $data['name']);
        Session::setAlert('success', 'Branch updated successfully.');
        $this->redirect(url('branches'));
    }

    /**
     * Delete branch
     */
    public function delete(int $id): void
    {
        Auth::requirePermission('branches_delete');

        $db = Database::getInstance();
        $branch = $db->table('branches')->find($id);

        if (!$branch) {
            Session::setAlert('danger', 'Branch not found.');
            $this->redirect(url('branches'));
            return;
        }

        $userCount = $db->table('users')->where('branch_id', $id)->count();
        if ($userCount > 0) {
            Session::setAlert('danger', 'Cannot delete branch with ' . $userCount . ' users assigned.');
            $this->redirect(url('branches'));
            return;
        }

        $db->table('branches')->delete($id);
        Auth::logActivity('branch_delete', 'Deleted branch: ' . $branch->name);
        Session::setAlert('success', 'Branch deleted successfully.');
        $this->redirect(url('branches'));
    }
}
