<?php

namespace App\Http\Controllers;

use App\Models\OrderConfirmation;
use App\Models\OrderDocument;
use App\Models\Quotation;
use App\Models\Seller;
use App\Models\Term;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class OrderConfirmationController extends Controller
{
    /**
     * Display a listing of order confirmations.
     */
// public function generatePiPdf($id)
// {
//     $order = OrderConfirmation::findOrFail($id);

//     // View path matches resources/views/admin/order_confirmations/invoice.blade.php
//     $pdf = \PDF::loadView('admin.order_confirmations.invoice', compact('order'));

//     return $pdf->download('PI-' . $order->order_number . '.pdf');
// }

//     public function generatePiPdf($id)
// {
//     $order = OrderConfirmation::findOrFail($id);

//     $pdf = \PDF::loadView('admin.order_confirmations.invoice', compact('order'));

//     return $pdf->stream('PI-' . $order->order_number . '.pdf');
// }


public function uploadBuyerPo(Request $request, $id)
{
    $order = OrderConfirmation::findOrFail($id);

    // Validate file type and size
    $request->validate([
        'pi_file' => 'required|mimes:pdf,jpg,jpeg,png|max:6048',
    ]);

    // Create folder if it doesn't exist
    $uploadPath = public_path('pi_file');
    if (!file_exists($uploadPath)) {
        mkdir($uploadPath, 0777, true);
    }

    // Handle file upload
    $file = $request->file('pi_file');
    $filename = 'pi_file' . time() . '.' . $file->getClientOriginalExtension();

    // Delete old file if it exists
    if ($order->pi_file && file_exists(public_path($order->pi_file))) {
        unlink(public_path($order->pi_file));
    }

    // Move new file to public/pi_file directory
    $file->move($uploadPath, $filename);

    // Save relative path in DB
    $order->pi_file = 'pi_file/' . $filename;
    $order->save();

    return back()->with('success', 'Buyer PO uploaded successfully!');
}




public function generatePiPdf($id)
{
    $order = OrderConfirmation::findOrFail($id);

    $piNumber = 'TEXASIA PI-'.str_pad($order->id, 10, '0', STR_PAD_LEFT);
    $seller = Seller::first();
    $terms = Term::all();

    $pdf = \PDF::loadView('admin.order_confirmations.invoice', compact('order', 'piNumber', 'seller','terms'));

    return $pdf->stream($piNumber . '.pdf');
}

public function generateScPdf($id)
{
    $order = OrderConfirmation::findOrFail($id);
$scNumber = 'TEXASIA-SC-' . str_pad($order->id, 10, '0', STR_PAD_LEFT);
  $seller = Seller::first();
    $terms = Term::all();
    // you might want to include terms from DB or a template
    $pdf = \PDF::loadView('admin.order_confirmations.sales_contract', compact('order', 'scNumber', 'seller','terms'))->setPaper('a4','portrait');

 

    return $pdf->stream($scNumber . '.pdf');
}


    public function index(Request $request)
    {
        $query = OrderConfirmation::with(['quotation.inquiry.itemDescription', 'quotation.inquiry.buyer']);

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter by delivery date range
        if ($request->filled('delivery_from')) {
            $query->where('delivery_date', '>=', $request->delivery_from);
        }
        if ($request->filled('delivery_to')) {
            $query->where('delivery_date', '<=', $request->delivery_to);
        }

        // Search by order number or customer PO
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('order_number', 'like', "%{$search}%")
                  ->orWhere('customer_po_number', 'like', "%{$search}%");
            });
        }

        // Sort by delivery date or created date
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        $orderConfirmations = $query->paginate(15);

        // Get status counts for dashboard
        $statusCounts = [
            'pending' => OrderConfirmation::where('status', 'pending')->count(),
            'confirmed' => OrderConfirmation::where('status', 'confirmed')->count(),
            'in_production' => OrderConfirmation::where('status', 'in_production')->count(),
            'shipped' => OrderConfirmation::where('status', 'shipped')->count(),
            'delivered' => OrderConfirmation::where('status', 'delivered')->count(),
            'overdue' => OrderConfirmation::where('delivery_date', '<', now())
                                         ->whereNotIn('status', ['delivered', 'cancelled'])
                                         ->count(),
        ];

        return view('admin.order_confirmations.index', compact('orderConfirmations', 'statusCounts'));
    }

    /**
     * Show the form for creating a new order confirmation.
     */
    public function create(Request $request)
    {
        $quotation_id = $request->query('quotation_id');
        
        if (!$quotation_id) {
            return redirect()->route('admin.quotations.index')
                           ->with('error', 'Quotation ID is required to create an order confirmation.');
        }

        $quotation = Quotation::with(['inquiry.itemDescription', 'inquiry.buyer', 'inquiry.brand'])
                             ->find($quotation_id);

        if (!$quotation) {
            return redirect()->route('admin.quotations.index')
                           ->with('error', 'Quotation not found.');
        }

        if ($quotation->status !== 'won') {
            return redirect()->route('admin.quotations.show', $quotation)
                           ->with('error', 'Only won quotations can be converted to orders.');
        }

        if ($quotation->orderConfirmation) {
            return redirect()->route('admin.order-confirmations.show', $quotation->orderConfirmation)
                           ->with('info', 'This quotation already has an order confirmation.');
        }

        return view('admin.order_confirmations.create', compact('quotation'));
    }

    /**
     * Store a newly created order confirmation.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'quotation_id' => 'required|exists:quotations,id',
            'customer_po_number' => 'nullable|string|max:255',
            'confirmed_quantity' => 'required|integer|min:1',
            'confirmed_price' => 'required|numeric|min:0',
            'delivery_date' => 'nullable|date|after:today',
            'payment_terms' => 'nullable|string',
            'special_instructions' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                           ->withErrors($validator)
                           ->withInput();
        }

        $quotation = Quotation::find($request->quotation_id);
        
        if ($quotation->status !== 'won') {
            return redirect()->back()
                           ->with('error', 'Only won quotations can be converted to orders.')
                           ->withInput();
        }

        if ($quotation->orderConfirmation) {
            return redirect()->route('admin.order-confirmations.show', $quotation->orderConfirmation)
                           ->with('info', 'This quotation already has an order confirmation.');
        }
 $orderData = $validator->validated();
    $orderData['created_by'] = auth()->id();
    $orderData['status'] = 'pending';

        $orderConfirmation = OrderConfirmation::create($orderData);

        return redirect()->route('admin.order-confirmations.show', $orderConfirmation)
                        ->with('success', 'Order confirmation created successfully.');
    }

    /**
     * Display the specified order confirmation.
     */
    public function show(OrderConfirmation $orderConfirmation)
    {
        $orderConfirmation->load([
            'quotation.inquiry.itemDescription',
            'quotation.inquiry.buyer',
            'quotation.inquiry.brand',
            'documents.uploader',
            'statusHistory.changedBy',
            'creator',
            'updater'
        ]);

        return view('admin.order_confirmations.show', compact('orderConfirmation'));
    }

    /**
     * Show the form for editing the specified order confirmation.
     */
    public function edit(OrderConfirmation $orderConfirmation)
    {
        $orderConfirmation->load(['quotation.inquiry.itemDescription', 'quotation.inquiry.buyer']);

        return view('admin.order-confirmations.edit', compact('orderConfirmation'));
    }

    /**
     * Update the specified order confirmation.
     */
    public function update(Request $request, OrderConfirmation $orderConfirmation)
    {
        $validator = Validator::make($request->all(), [
            'customer_po_number' => 'nullable|string|max:255',
            'confirmed_quantity' => 'required|integer|min:1',
            'confirmed_price' => 'required|numeric|min:0',
            'delivery_date' => 'nullable|date',
            'payment_terms' => 'nullable|string',
            'special_instructions' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                           ->withErrors($validator)
                           ->withInput();
        }

        $orderConfirmation->update($request->validated() + ['updated_by' => auth()->id()]);

        return redirect()->route('admin.order-confirmations.show', $orderConfirmation)
                        ->with('success', 'Order confirmation updated successfully.');
    }

    /**
     * Remove the specified order confirmation.
     */
    public function destroy(OrderConfirmation $orderConfirmation)
    {
        // Check if order can be deleted (only pending orders)
        if (!in_array($orderConfirmation->status, ['pending', 'cancelled'])) {
            return redirect()->back()
                           ->with('error', 'Only pending or cancelled orders can be deleted.');
        }

        $orderConfirmation->delete();

        return redirect()->route('admin.order-confirmations.index')
                        ->with('success', 'Order confirmation deleted successfully.');
    }

    /**
     * Update the status of an order confirmation.
     */
 public function updateStatus(Request $request, OrderConfirmation $orderConfirmation)
{
    $validator = Validator::make($request->all(), [
        'status' => 'required|in:pending,confirmed,in_production,shipped,delivered,cancelled',
        'notes' => 'nullable|string|max:1000',
    ]);

    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }

    $oldStatus = $orderConfirmation->status;

    // Only update and save if the status has actually changed
    if ($oldStatus !== $request->status) {
        $orderConfirmation->status = $request->status;
        $orderConfirmation->updated_by = auth()->id();
        $orderConfirmation->save();

        // Record status change in history ONLY if status changed
        $orderConfirmation->statusHistory()->create([
            'previous_status' => $oldStatus,
            'new_status' => $request->status,
            'notes' => $request->notes,
            'changed_by' => auth()->id(),
            'changed_at' => now(),
        ]);
    }

    if ($request->expectsJson()) {
        return response()->json([
            'success' => true,
            'message' => 'Status updated successfully.',
            'status' => $orderConfirmation->status,
            'status_label' => $orderConfirmation->status_label,
            'status_badge_color' => $orderConfirmation->status_badge_color,
        ]);
    }

    return redirect()->back()->with('success', 'Order status updated successfully.');
}


    /**
     * Upload a document for an order confirmation.
     */
    public function uploadDocument(Request $request, OrderConfirmation $orderConfirmation)
    {
        $validator = Validator::make($request->all(), [
            'document_type' => 'required|in:purchase_order,invoice,packing_list,shipping_document,quality_certificate,fabric_specification,production_schedule,other',
            'document_name' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'file' => 'required|file|max:10240|mimes:pdf,doc,docx,xls,xlsx,jpg,jpeg,png,gif',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                           ->withErrors($validator)
                           ->withInput();
        }

        $file = $request->file('file');
        $fileName = time() . '_' . Str::slug($request->document_name) . '.' . $file->getClientOriginalExtension();
        $filePath = $file->storeAs('order_documents/' . $orderConfirmation->id, $fileName, 'public');

        $orderConfirmation->documents()->create([
            'document_type' => $request->document_type,
            'document_name' => $request->document_name,
            'description' => $request->description,
            'file_path' => $filePath,
            'file_size' => $file->getSize(),
            'mime_type' => $file->getMimeType(),
            'uploaded_by' => auth()->id(),
            'uploaded_at' => now(),
        ]);

        return redirect()->back()->with('success', 'Document uploaded successfully.');
    }

    /**
     * Download a document.
     */
    public function downloadDocument(OrderConfirmation $orderConfirmation, OrderDocument $document)
    {
        if ($document->order_confirmation_id !== $orderConfirmation->id) {
            abort(404);
        }

        if (!Storage::disk('public')->exists($document->file_path)) {
            return redirect()->back()->with('error', 'File not found.');
        }

        return Storage::disk('public')->download($document->file_path, $document->document_name);
    }

    /**
     * Delete a document.
     */
    public function deleteDocument(OrderConfirmation $orderConfirmation, OrderDocument $document)
    {
        if ($document->order_confirmation_id !== $orderConfirmation->id) {
            abort(404);
        }

        $document->delete();

        return redirect()->back()->with('success', 'Document deleted successfully.');
    }

    /**
     * Get dashboard data for order confirmations.
     */
    public function dashboard()
    {
        $stats = [
            'total_orders' => OrderConfirmation::count(),
            'pending_orders' => OrderConfirmation::where('status', 'pending')->count(),
            'in_production' => OrderConfirmation::where('status', 'in_production')->count(),
            'overdue_orders' => OrderConfirmation::where('delivery_date', '<', now())
                                              ->whereNotIn('status', ['delivered', 'cancelled'])
                                              ->count(),
            'total_value' => OrderConfirmation::whereNotIn('status', ['cancelled'])
                                            ->sum(\DB::raw('confirmed_quantity * confirmed_price')),
        ];

        $recentOrders = OrderConfirmation::with(['quotation.inquiry.itemDescription', 'quotation.inquiry.buyer'])
                                        ->latest()
                                        ->limit(10)
                                        ->get();

        $upcomingDeliveries = OrderConfirmation::with(['quotation.inquiry.itemDescription', 'quotation.inquiry.buyer'])
                                             ->where('delivery_date', '>=', now())
                                             ->where('delivery_date', '<=', now()->addDays(7))
                                             ->whereIn('status', ['confirmed', 'in_production'])
                                             ->orderBy('delivery_date')
                                             ->get();

        return view('admin.order-confirmations.dashboard', compact('stats', 'recentOrders', 'upcomingDeliveries'));
    }
}

