<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Response;
use App\Models\VendorModel;
use App\Models\AuditLogModel;

/**
 * Vendor Management Controller
 */
class VendorController extends Controller
{
    private VendorModel $vendorModel;
    private AuditLogModel $auditLogger;

    public function __construct()
    {
        $this->vendorModel = new VendorModel();
        $this->auditLogger = new AuditLogModel();
    }

    public function index(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $filters = [
            'search' => $_GET['search'] ?? null,
            'status' => $_GET['status'] ?? 'active',
            'sort' => $_GET['sort'] ?? 'name',
            'order' => $_GET['order'] ?? 'ASC'
        ];
        $page = (int) ($_GET['page'] ?? 1);
        $perPage = (int) ($_GET['per_page'] ?? 20);

        $vendors = $this->vendorModel->getAll($tenantId, $filters, $page, $perPage);
        $total = $this->vendorModel->countAll($tenantId, $filters);

        Response::paginated($vendors, $total, $page, $perPage);
    }

    public function store(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $userId = (int) $_REQUEST['user']['sub'];
        $data = $this->getJsonBody();

        $this->validate($data, [
            'name' => 'required|min:2'
        ]);

        $allowed = ['name', 'company_name', 'email', 'phone', 'address', 'city', 'state', 'pincode', 'country', 'payment_terms', 'opening_balance', 'bank_name', 'bank_account', 'bank_ifsc', 'status', 'notes'];
        $cleanData = [];
        foreach ($allowed as $field) {
            if (isset($data[$field])) {
                $cleanData[$field] = $data[$field] === '' ? null : $data[$field];
            }
        }

        $cleanData['tenant_id'] = $tenantId;
        $cleanData['created_by'] = $userId;

        $id = $this->vendorModel->create($cleanData);
        if ($id) {
            $this->auditLogger->log($tenantId, $userId, 'create', 'vendors', (int) $id, null, $cleanData);
            Response::success(['id' => $id], 'Vendor created successfully', 201);
        }
        Response::error('Failed to create vendor');
    }

    public function show(string $id): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $vendor = $this->vendorModel->getById((int) $id, $tenantId);
        if (!$vendor)
            Response::error('Vendor not found', [], 404);
        Response::success($vendor);
    }

    public function update(string $id): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $userId = (int) $_REQUEST['user']['sub'];
        $data = $this->getJsonBody();

        $old = $this->vendorModel->getById((int) $id, $tenantId);
        if (!$old)
            Response::error('Vendor not found', [], 404);

        $allowed = ['name', 'company_name', 'email', 'phone', 'address', 'city', 'state', 'pincode', 'country', 'payment_terms', 'opening_balance', 'bank_name', 'bank_account', 'bank_ifsc', 'status', 'notes'];
        $cleanData = [];
        foreach ($allowed as $field) {
            if (isset($data[$field])) {
                $cleanData[$field] = $data[$field] === '' ? null : $data[$field];
            }
        }

        if ($this->vendorModel->update((int) $id, $cleanData)) {
            $this->auditLogger->log($tenantId, $userId, 'update', 'vendors', (int) $id, $old, $cleanData);
            Response::success([], 'Vendor updated successfully');
        }
        Response::error('Update failed');
    }

    public function destroy(string $id): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $userId = (int) $_REQUEST['user']['sub'];
        if ($this->vendorModel->softDelete((int) $id, $tenantId, $userId)) {
            Response::success([], 'Vendor deactivated');
        }
        Response::error('Delete failed');
    }
}
