<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\OrderConfirmation;
use App\Models\OrderDocument;

class OrderDocumentController extends Controller
{
    /**
     * Show the form for creating a new document.
     */
    public function create($order_confirmation_id)
    {
        $orderConfirmation = OrderConfirmation::findOrFail($order_confirmation_id);
        return view('admin.order_documents.create', compact('orderConfirmation'));
    }

    /**
     * Store a newly created document in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
    'order_confirmation_id' => 'required|exists:order_confirmations,id',
    'document_file' => 'required|file|mimes:pdf,doc,docx,xls,xlsx,jpg,jpeg,png|max:30240',
    'document_type' => 'required|in:purchase_order,invoice,packing_list,shipping_document,quality_certificate,other',
    'notes' => 'nullable|string|max:1000',
]);


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

        try {
            $orderConfirmation = OrderConfirmation::findOrFail($request->order_confirmation_id);
            
            // Handle file upload
            $file = $request->file('document_file');
            $originalName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $fileName = time() . '_' . str_replace(' ', '_', $originalName);
            
            // Store file in storage/app/order_documents
            $filePath = $file->storeAs('order_documents', $fileName);
            
            // Create database record
      $document = OrderDocument::create([
    'order_confirmation_id' => $orderConfirmation->id,
    'file_name' => $originalName,
    'file_path' => $filePath,
    'file_size' => $file->getSize(),
    'mime_type' => $file->getMimeType(),
    'document_type' => $request->document_type, // ← updated
    'notes' => $request->notes,
    'uploaded_by' => Auth::id(),
]);


            return redirect()->route('admin.order-confirmations.show', $orderConfirmation->id)
                           ->with('success', 'Document uploaded successfully!');

        } catch (\Exception $e) {
            return redirect()->back()
                           ->with('error', 'Failed to upload document: ' . $e->getMessage())
                           ->withInput();
        }
    }

    /**
     * Download the specified document.
     */
    public function download(OrderDocument $orderDocument)
    {
        try {
            $filePath = storage_path('app/' . $orderDocument->file_path);
            
            if (!file_exists($filePath)) {
                return redirect()->back()->with('error', 'File not found.');
            }

            return response()->download($filePath, $orderDocument->file_name);

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to download file: ' . $e->getMessage());
        }
    }

    /**
     * Remove the specified document from storage.
     */
    public function destroy(OrderDocument $orderDocument)
    {
        try {
            // Delete file from storage
            if (Storage::exists($orderDocument->file_path)) {
                Storage::delete($orderDocument->file_path);
            }

            // Delete database record
            $orderDocument->delete();

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

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to delete document: ' . $e->getMessage());
        }
    }

    /**
     * Display a listing of documents for a specific order confirmation.
     */
    public function index($order_confirmation_id)
    {
        $orderConfirmation = OrderConfirmation::with('documents.uploader')->findOrFail($order_confirmation_id);
        return view('admin.order_documents.index', compact('orderConfirmation'));
    }

    /**
     * Show the form for editing the specified document.
     */
    public function edit(OrderDocument $orderDocument)
    {
        return view('admin.order_documents.edit', compact('orderDocument'));
    }

    /**
     * Update the specified document in storage.
     */
    public function update(Request $request, OrderDocument $orderDocument)
    {
        $validator = Validator::make($request->all(), [
            'category' => 'required|in:purchase_order,invoice,packing_list,shipping_document,quality_certificate,other',
            'notes' => 'nullable|string|max:1000',
        ]);

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

        try {
            $orderDocument->update([
                'category' => $request->category,
                'notes' => $request->notes,
            ]);

            return redirect()->route('admin.order-confirmations.show', $orderDocument->order_confirmation_id)
                           ->with('success', 'Document updated successfully!');

        } catch (\Exception $e) {
            return redirect()->back()
                           ->with('error', 'Failed to update document: ' . $e->getMessage())
                           ->withInput();
        }
    }
}

