<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Tender;
use App\Models\TenderLineItem;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TenderController extends Controller
{
    /**
     * Step 1: Store/Update basic tender information
     * Fields: project_id, title, closing_date, reference (auto-generated)
     */
    public function step1(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'nullable|integer|exists:tenders,id',
            'project_id' => 'required|integer|exists:projects,id',
            'title' => 'required|string|max:255',
            'closing_date' => 'required|date',
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        // Get customer_id and workspace_id
        $ids = $this->getCustomerAndWorkspaceIds();
        if (!$ids) {
            return $this->message('Unable to determine customer or workspace', 400);
        }
        $data = [
            'project_id' => $request->project_id,
            'title' => $request->title,
            'closing_date' => $request->closing_date,
            'customer_id' => $ids['customer_id'],
            'workspace_id' => $ids['workspace_id'],
            'status' => 'draft',
        ];
        if ($request->filled('id')) {
            // Update existing tender
            $tender = Tender::find($request->id);
            $tender->update($data);
            $message = 'Tender updated successfully';
        } else {
            // Create new tender (reference will be auto-generated in boot method)
            $tender = Tender::create($data);
            $message = 'Tender created successfully';
        }
        return $this->success($tender, $message);
    }

    /**
     * Step 2: Store/Update scope of work and line items
     * Fields: scope_of_work, line_items (array with description, unit, quantity)
     */
    public function step2(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer|exists:tenders,id',
            'scope_of_work' => 'nullable|string',
            'line_items' => 'required|array|min:1',
            'line_items.*.description' => 'required|string',
            'line_items.*.unit' => 'required|string|max:50',
            'line_items.*.quantity' => 'required|integer|min:1',
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        // Get customer_id and workspace_id and verify tender ownership
        $ids = $this->getCustomerAndWorkspaceIds();
        if (!$ids) {
            return $this->message('Unable to determine customer or workspace', 400);
        }
        $query = Tender::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        $tender = $query->find($request->id);
        if (!$tender) {
            return $this->message('Tender not found or you do not have access', 404);
        }
        // Update scope of work
        $tender->scope_of_work = $request->scope_of_work;
        $tender->save();
        // Delete existing line items for this tender
        TenderLineItem::where('tender_id', $tender->id)->delete();
        // Create new line items
        $lineItems = [];
        foreach ($request->line_items as $item) {
            $lineItems[] = TenderLineItem::create([
                'tender_id' => $tender->id,
                'description' => $item['description'],
                'unit' => $item['unit'],
                'quantity' => $item['quantity'],
                'customer_id' => $ids['customer_id'],
                'workspace_id' => $ids['workspace_id'],
            ]);
        }
        // Reload tender with line items
        $tender->load('lineItems');
        return $this->success($tender, 'Tender line items saved successfully');
    }

    /**
     * Step 3: Store/Update tender settings
     * Fields: reminder_days_before, allow_late_submissions, allow_bidder_document_uploads
     */
    public function step3(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer|exists:tenders,id',
            'reminder_days_before' => 'nullable|integer|min:0',
            'allow_late_submissions' => 'nullable|boolean',
            'allow_bidder_document_uploads' => 'nullable|boolean',
        ]);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }

        // Get customer_id and workspace_id and verify tender ownership
        $ids = $this->getCustomerAndWorkspaceIds();
        if (!$ids) {
            return $this->message('Unable to determine customer or workspace', 400);
        }

        $query = Tender::query();
        $query = $this->applyCustomerWorkspaceFilter($query);
        $tender = $query->find($request->id);

        if (!$tender) {
            return $this->message('Tender not found or you do not have access', 404);
        }
        $data = [];
        if ($request->has('reminder_days_before')) {
            $data['reminder_days_before'] = $request->reminder_days_before;
        }
        if ($request->has('allow_late_submissions')) {
            $data['allow_late_submissions'] = $request->allow_late_submissions;
        }
        if ($request->has('allow_bidder_document_uploads')) {
            $data['allow_bidder_document_uploads'] = $request->allow_bidder_document_uploads;
        }
        $tender->update($data);
        return $this->success($tender, 'Tender settings saved successfully');
    }



    /**
     * Get step data for tender form
     * Accepts step (step1, step2, step3) and tender_id (optional)
     * Returns data according to the step
     */
    public function getStepData(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'step' => 'required|string|in:step0,step1,step2',
            'tender_id' => 'nullable|integer|exists:tenders,id',
        ]);

        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }

        $step = $request->step;
        $tenderId = $request->tender_id;

        // Apply customer workspace filter
        $query = Tender::query();
        $query = $this->applyCustomerWorkspaceFilter($query);

        // If tender_id is provided, verify ownership and get tender
        $tender = null;
        if ($tenderId) {
            $tender = $query->find($tenderId);
            if (!$tender) {
                return $this->message('Tender not found or you do not have access', 404);
            }
        }

        $data = [];

        switch ($step) {
            case 'step0':
                // Step 0: Basic information
                if ($tender) {
                    $data = [
                        'project_id' => $tender->project_id,
                        'title' => $tender->title,
                        'closing_date' => $tender->closing_date,
                        'reference' => $tender->reference,
                        'status' => $tender->status,
                    ];
                } else {
                    // Return empty structure for new tender
                    $data = [
                        'project_id' => null,
                        'title' => null,
                        'closing_date' => null,
                        'reference' => null,
                        'status' => 'draft',
                    ];
                }
                break;

            case 'step1':
                // Step 1: Scope of work and line items
                if ($tender) {
                    $tender->load('lineItems');
                    $data = [
                        'scope_of_work' => $tender->scope_of_work,
                        'line_items' => $tender->lineItems->map(function ($item) {
                            return [
                                'id' => $item->id,
                                'description' => $item->description,
                                'unit' => $item->unit,
                                'quantity' => $item->quantity,
                            ];
                        })->toArray(),
                    ];
                } else {
                    // Return empty structure for new tender
                    $data = [
                        'scope_of_work' => null,
                        'line_items' => [],
                    ];
                }
                break;

            case 'step2':
                // Step 2: Settings
                if ($tender) {
                    $data = [
                        'reminder_days_before' => $tender->reminder_days_before,
                        'allow_late_submissions' => $tender->allow_late_submissions ?? false,
                        'allow_bidder_document_uploads' => $tender->allow_bidder_document_uploads ?? false,
                    ];
                } else {
                    // Return default values for new tender
                    $data = [
                        'reminder_days_before' => null,
                        'allow_late_submissions' => false,
                        'allow_bidder_document_uploads' => false,
                    ];
                }
                break;

            default:
                return $this->message('Invalid step provided', 400);
        }
        $data['step'] = $step;
        $data['tender_id'] = $tenderId;
        return $this->success($data, ucfirst($step) . ' data retrieved successfully');
    }

    /**
     * Get tender by ID
     */
    public function show($id)
    {

        $query = Tender::with(['lineItems', 'project', 'participants', 'rfis']);
        // Apply customer workspace filter
        $query = $this->applyCustomerWorkspaceFilter($query);
        $tender = $query->find($id);
        return $this->success($tender, 'Tender retrieved successfully');
    }

    /**
     * List all tenders
     */
    public function index(Request $request)
    {
        $query = Tender::with(['project', 'lineItems']);
        // Apply customer workspace filter if needed
        $query = $this->applyCustomerWorkspaceFilter($query);
        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', '%' . $search . '%')
                    ->orWhere('reference', 'like', '%' . $search . '%')
                    ->orWhereHas('project', function ($subquery) use ($search) {
                        $subquery->where('title', 'like', '%' . $search . '%');
                    });
            });
        }
        // Filter by project
        if ($request->filled('project_id')) {
            $query->where('project_id', $request->project_id);
        }
        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        return $this->withCount($query, 'Tenders retrieved successfully');
    }

    /**
     * Delete tender
     */
    public function destroy($id)
    {
        $query = Tender::query();
        // Apply customer workspace filter
        $query = $this->applyCustomerWorkspaceFilter($query);
        $tender = $query->find($id);
        if (!$tender) {
            return $this->message('Tender not found', 404);
        }
        // Delete related records
        TenderLineItem::where('tender_id', $tender->id)->delete();
        $tender->delete();
        return $this->message('Tender deleted successfully', 200);
    }
}
