<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Quotation;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class QuotationController extends Controller
{
    /**
     * Get all quotations for a user
     */
    public function index(Request $request)
    {
        $userId = $request->query('user_id');
        
        $query = Quotation::with(['user', 'creator']);
        
        if ($userId) {
            $query->where('user_id', $userId);
        }
        
        $quotations = $query->orderBy('created_at', 'desc')->get();
        
        return response()->json([
            'success' => true,
            'data' => $quotations
        ]);
    }

    /**
     * Get a single quotation
     */
    public function show($id)
    {
        $quotation = Quotation::with(['user', 'creator'])->findOrFail($id);
        
        return response()->json([
            'success' => true,
            'data' => $quotation
        ]);
    }

    /**
     * Create a new quotation
     */
    public function store(Request $request)
    {
        // Decode items if it's a JSON string (from FormData)
        if ($request->has('items') && is_string($request->input('items'))) {
            $request->merge(['items' => json_decode($request->input('items'), true)]);
        }
        
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
            'customer_name' => 'required|string|max:255',
            'customer_email' => 'required|email|max:255',
            'items' => 'required|array|min:1',
            'items.*.description' => 'required|string',
            'items.*.quantity' => 'required|integer|min:1',
            'items.*.price' => 'required|numeric|min:0',
            'notes' => 'nullable|string|max:1000',
            'total_amount' => 'required|numeric|min:0.50',
            'currency' => 'nullable|string|size:3',
            'agreement_file' => 'nullable|file|mimes:pdf,doc,docx|max:10240',
        ]);

        try {
            // Handle file upload
            $agreementFileName = null;
            $agreementFilePath = null;
            
            if ($request->hasFile('agreement_file')) {
                $file = $request->file('agreement_file');
                $fileName = time() . '_' . $file->getClientOriginalName();
                $filePath = $file->storeAs('quotations/agreements', $fileName, 'public');
                $agreementFileName = $fileName;
                $agreementFilePath = $filePath;
            }
            
            // Create quotation record
            $quotation = Quotation::create([
                'user_id' => $validated['user_id'],
                'created_by' => $request->user()->id,
                'customer_name' => $validated['customer_name'],
                'customer_email' => $validated['customer_email'],
                'items' => $validated['items'],
                'notes' => $validated['notes'] ?? null,
                'agreement_file_name' => $agreementFileName,
                'agreement_file_path' => $agreementFilePath,
                'total_amount' => $validated['total_amount'],
                'currency' => $validated['currency'] ?? 'usd',
                'status' => 'pending',
            ]);

            Log::info('Quotation created', [
                'quotation_id' => $quotation->id,
                'user_id' => $quotation->user_id,
                'total_amount' => $quotation->total_amount,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Quotation created successfully',
                'data' => $quotation->load(['user', 'creator'])
            ], 201);

        } catch (\Exception $e) {
            Log::error('Failed to create quotation', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to create quotation'
            ], 500);
        }
    }

    /**
     * Update quotation status
     */
    public function updateStatus(Request $request, $id)
    {
        $validated = $request->validate([
            'status' => 'required|in:pending,sent,accepted,rejected',
            'stripe_invoice_id' => 'nullable|string',
            'hosted_invoice_url' => 'nullable|string',
        ]);

        $quotation = Quotation::findOrFail($id);
        
        $quotation->update([
            'status' => $validated['status'],
            'stripe_invoice_id' => $validated['stripe_invoice_id'] ?? $quotation->stripe_invoice_id,
            'hosted_invoice_url' => $validated['hosted_invoice_url'] ?? $quotation->hosted_invoice_url,
            'sent_at' => $validated['status'] === 'sent' && !$quotation->sent_at ? now() : $quotation->sent_at,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Quotation status updated',
            'data' => $quotation->load(['user', 'creator'])
        ]);
    }

    /**
     * Delete a quotation
     */
    public function destroy($id)
    {
        $quotation = Quotation::findOrFail($id);
        $quotation->delete();

        return response()->json([
            'success' => true,
            'message' => 'Quotation deleted successfully'
        ]);
    }
}
