<?php

namespace App\Http\Controllers\Base;

use App\Services\Sales\RfqService;
use App\Models\CustomerVendor;
use App\Models\RfqType;
use App\Models\ProductType;
use App\Models\RawMaterial;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class BaseRfqController extends BaseController
{
    protected string $module = 'rfq';
    protected string $displayName = 'RFQ';
    protected array $listRelations = ['customerInfo'];
    protected array $showRelations = ['customerInfo', 'rfqFiles'];

    protected RfqService $rfqService;

    public function __construct(RfqService $service)
    {
        parent::__construct($service);
        $this->rfqService = $service;
    }

    /**
     * Display a listing of RFQs
     */
    public function index()
    {
        return $this->roleView('rfq.index');
    }

    /**
     * Get RFQs for DataTable
     */
    public function list()
    {
        $query = $this->rfqService->getForDataTable();

        return DataTables::of($query)
            ->addIndexColumn()
            ->addColumn('customer_name', function ($row) {
                return $row->customerInfo?->company_name ?? 'N/A';
            })
            ->addColumn('action', function ($row) {
                return $this->getRfqActionButtons($row);
            })
            ->rawColumns(['action'])
            ->make(true);
    }

    /**
     * Generate action buttons for RFQ
     */
    protected function getRfqActionButtons($row): string
    {
        $showRoute = route($this->resolveRoute('rfq.show'), $row->id);
        $editRoute = route($this->resolveRoute('rfq.edit'), $row->id);
        $createQuotationRoute = route($this->resolveRoute('quotation.createFromRfq'), $row->id);

        return '
            <a href="' . $showRoute . '" class="btn btn-info btn-sm" title="View">
                <i class="fas fa-eye"></i>
            </a>
            <a href="' . $editRoute . '" class="btn btn-primary btn-sm" title="Edit">
                <i class="fas fa-edit"></i>
            </a>
            <a href="' . $createQuotationRoute . '" class="btn btn-success btn-sm" title="Create Quotation">
                <i class="fas fa-file-invoice"></i>
            </a>
            <button class="btn btn-danger btn-sm delete-btn" data-id="' . $row->id . '" title="Delete">
                <i class="fas fa-trash"></i>
            </button>
        ';
    }

    /**
     * Show the form for creating a new RFQ
     */
    public function create()
    {
        $data = $this->getCreateData();
        $data['rfq_no'] = $this->rfqService->generateRfqNumber();
        return $this->roleView('rfq.create', $data);
    }

    /**
     * Get additional data for create/edit forms
     */
    protected function getCreateData(): array
    {
        return [
            'customers' => CustomerVendor::where('company_role', '!=', 'Vendor')->orderBy('company_name')->get(),
            'rfqTypes' => RfqType::orderBy('name')->get(),
            'productTypes' => ProductType::orderBy('name')->get(),
            'rawMaterials' => RawMaterial::orderBy('name')->get(),
        ];
    }

    /**
     * Store a newly created RFQ
     */
    public function store(Request $request)
    {
        $validated = $this->validateStore($request);

        try {
            $files = $request->file('files', []);
            $rfq = $this->rfqService->createWithFiles($validated, $files);

            return $this->redirectToRoute('rfq.index')
                ->with('success', 'RFQ created successfully.');
        } catch (\Exception $e) {
            return back()
                ->withInput()
                ->with('error', 'Failed to create RFQ: ' . $e->getMessage());
        }
    }

    /**
     * Display the specified RFQ
     */
    public function show(int $id)
    {
        $rfq = $this->rfqService->findByIdWith($id, $this->showRelations);

        if (!$rfq) {
            return $this->redirectToRoute('rfq.index')
                ->with('error', 'RFQ not found.');
        }

        return $this->roleView('rfq.show', compact('rfq'));
    }

    /**
     * Show the form for editing the specified RFQ
     */
    public function edit(int $id)
    {
        $rfq = $this->rfqService->findByIdWith($id, $this->showRelations);

        if (!$rfq) {
            return $this->redirectToRoute('rfq.index')
                ->with('error', 'RFQ not found.');
        }

        $data = $this->getCreateData();
        $data['rfq'] = $rfq;

        return $this->roleView('rfq.edit', $data);
    }

    /**
     * Update the specified RFQ
     */
    public function update(Request $request, int $id)
    {
        $validated = $this->validateUpdate($request, $id);

        try {
            $files = $request->file('files', []);
            $rfq = $this->rfqService->updateWithFiles($id, $validated, $files);

            return $this->redirectToRoute('rfq.index')
                ->with('success', 'RFQ updated successfully.');
        } catch (\Exception $e) {
            return back()
                ->withInput()
                ->with('error', 'Failed to update RFQ: ' . $e->getMessage());
        }
    }

    /**
     * Remove the specified RFQ
     */
    public function destroy(int $id)
    {
        try {
            $this->rfqService->deleteWithFiles($id);

            return $this->jsonSuccess('RFQ deleted successfully.');
        } catch (\Exception $e) {
            return $this->jsonError('Failed to delete RFQ.', 500);
        }
    }

    /**
     * Delete a specific file from RFQ
     */
    public function deleteFile(int $fileId)
    {
        try {
            $this->rfqService->deleteFile($fileId);

            return $this->jsonSuccess('File deleted successfully.');
        } catch (\Exception $e) {
            return $this->jsonError('Failed to delete file.', 500);
        }
    }

    /**
     * Get validation rules
     */
    protected function getValidationRules(): array
    {
        return [
            'rfq_no' => 'nullable|string|max:50',
            'rfq_date' => 'required|date',
            'customer' => 'required|exists:customer_vendors,id',
            'cus_ref_no' => 'nullable|string|max:100',
            'rfq_type' => 'nullable|string|max:100',
            'product_type' => 'nullable|string|max:100',
            'part_no' => 'nullable|string|max:100',
            'project_material_no' => 'nullable|string|max:100',
            'description' => 'nullable|string',
            'drawing_no' => 'nullable|string|max:100',
            'drawing_rev' => 'nullable|string|max:50',
            'quantity' => 'nullable|numeric|min:0',
            'uom' => 'nullable|string|max:50',
            'note' => 'nullable|string',
            'raw_material' => 'nullable|string|max:255',
        ];
    }

    /**
     * Search RFQs (AJAX)
     */
    public function search(Request $request)
    {
        $term = $request->input('q', '');
        $rfqs = $this->rfqService->search($term);

        return response()->json([
            'results' => $rfqs->map(function ($rfq) {
                return [
                    'id' => $rfq->id,
                    'text' => $rfq->rfq_no . ' - ' . ($rfq->customerInfo?->company_name ?? 'N/A'),
                ];
            }),
        ]);
    }
}
