<?php

namespace App\Http\Controllers\Backend\Order;

use App\Http\Controllers\Controller;
use App\Models\Buyer;
use App\Models\Company;
use App\Models\Order;
use App\Models\OrderAttachment;
use App\Models\OrderDetails;
use App\Models\ProformaInvoice;
use App\Models\Project;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class ProformaInvoiceController extends Controller {
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        $title = "Proforma Invoice";
        $buyer = Auth::guard('buyer')->user();
        if ($buyer) {
            $profirmaInvoices = ProformaInvoice::orderBy('id', 'DESC')->where('buyer_id', $buyer->id)->get();
        } else {
            $profirmaInvoices = ProformaInvoice::orderBy('id', 'DESC')->get();
        }
        $projectLastData = Project::latest('id')->first();
        if ($projectLastData) :
            $projectData = $projectLastData->id + 1;
        else :
            $projectData = 1;
        endif;
        $projectCode = 'PRJ' . str_pad($projectData, 5, "0", STR_PAD_LEFT);
        $managers = User::get()->whereNotIn('id', [1])->where('status', 'Active');
        return view('backend.pages.order.proforma_invoice.index', get_defined_vars());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        $title = "Add New PI";
        $pi = ProformaInvoice::pluck('order_id');
        $orders = Order::where('status', 'Approved')->whereNotIn('id', $pi)->get();
        return view('backend.pages.order.proforma_invoice.create', get_defined_vars());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $validate = Validator::make($request->all(), [
            'pi_number' => 'required|string|max:15|min:2',
            'pi_date' => 'required|string',
            'vat_number' => 'required|string|max:15|min:2',
            'order_id' => 'required|numeric',
            'buyer_id' => 'required|numeric',
        ]);
        if ($validate->fails()) {
            return back()->with('warning', 'Validation error');
        }
        $pi = new ProformaInvoice();
        $pi->pi_number = $request->pi_number;
        $pi->pi_date = $request->pi_date;
        $pi->vat_number = $request->vat_number;
        $pi->order_id = $request->order_id;
        $pi->buyer_id = $request->buyer_id;
        // $pi->status = 'Pending';
        $pi->created_by = Auth::user()->id;
        $pi->save();

        return redirect()->route('proforma.invoice.list')->with('success', 'PI Generated Successfully!');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\ProformaInvoice  $proformaInvoice
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        $title = "Proforma Invoice";
        $pi = ProformaInvoice::find($id);
        $companyInfo = Company::where('status', 'Active')->first();
        $orders = Order::where('status', 'Approved')->get();
        $invoice = $pi->order;
        return view('backend.pages.order.proforma_invoice.invoice', get_defined_vars());
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\ProformaInvoice  $proformaInvoice
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        $title = "Edit PI";
        $pi = ProformaInvoice::find($id);
        $order = Order::where('id', $pi->order_id)->first();
        // dd($order);
        $invoice = $pi->order;
        return view('backend.pages.order.proforma_invoice.edit', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\ProformaInvoice  $proformaInvoice
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        // dd($request->all());
        $validate = Validator::make($request->all(), [
            'pi_number' => 'required|string|max:15|min:2',
            'pi_date' => 'required|string',
            'vat_number' => 'required|string|max:15|min:2',
        ]);
        if ($validate->fails()) {
            return back()->with('warning', 'Validation error');
        }
        $pi = ProformaInvoice::find($id);
        $pi->pi_number = $request->pi_number;
        $pi->pi_date = $request->pi_date;
        $pi->vat_number = $request->vat_number;
        $pi->note = $request->note;
        $pi->updated_by = Auth::user()->id;
        $pi->save();

        $attachments = $request->file('attachments');
        if ($attachments != null) {
            foreach ($attachments as $key => $attachment) {
                $orderAttachment = 'attachment_' . time() . '_' . $key . '.' . $attachment->getClientOriginalExtension();
                $attachment->move(public_path('/uploads/orders/'), $orderAttachment);
                $orderFile = new OrderAttachment();
                $orderFile->order_id = $pi->order_id;
                $orderFile->buyer_id = $pi->buyer_id;
                $orderFile->type = 'PI';
                $orderFile->attachment = $orderAttachment;
                $orderFile->save();
            }
        }

        $details = OrderDetails::where('order_id', $pi->order_id)->get();

        if (!$details) {
            return back()->with('error', 'Order details not found!');
        }
        if ($request->has('hs_code')) {
            foreach ($request->hs_code as $key => $hs_code) {
                if (isset($details[$key])) {
                    $details[$key]->hs_code = $hs_code;
                    $details[$key]->save();
                }
            }
        }

        if ($request->has('rate')) {
            foreach ($request->rate as $key => $rate) {
                if (isset($details[$key])) {
                    $details[$key]->rate = $rate;
                    $details[$key]->save();
                }
            }
        }
        $pi->order->update(['amount' => array_sum($request->price)]);
        if ($request->has('price')) {
            foreach ($request->price as $key => $price) {
                if (isset($details[$key])) {
                    $details[$key]->price = $price;
                    $details[$key]->save();
                }
            }
        }

        return redirect()->route('proforma.invoice.list')->with('success', 'PI updated Successfully!');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\ProformaInvoice  $proformaInvoice
     * @return \Illuminate\Http\Response
     */
    public function destroy(ProformaInvoice $proformaInvoice)
    {
        //
    }

    public function status($id, $status) {
        $pi = ProformaInvoice::find($id);
        $order = Order::find($pi->order_id);
        $order->status = $status;
        $order->save();

        return redirect()->route('buyer.proforma.invoice.list');
    }

    public function generate(Request $request) {
        $validate = Validator::make($request->all(), [
            'pi_number' => 'required|string|max:15|min:2',
            'pi_date' => 'required|string',
            'vat_number' => 'required|string|max:15|min:2',
            'order_id' => 'required|numeric',
            'buyer_id' => 'required|numeric',
        ]);
    
        if ($validate->fails()) {
            return back()->with('warning', 'Validation error');
        }
    
        $existingPI = ProformaInvoice::where('order_id', $request->order_id)->first();
        if ($existingPI) {
            return back()->with('warning', 'PI has already been generated for this order');
        }

        // $order = Order::find('id', $request->order_id);
        // $order->status = 'Approved';
        // $order->save();
    
        $pi = new ProformaInvoice();
        $pi->pi_number = $request->pi_number;
        $pi->pi_date = $request->pi_date;
        $pi->vat_number = $request->vat_number;
        $pi->order_id = $request->order_id;
        $pi->buyer_id = $request->buyer_id;
        $pi->created_by = Auth::user()->id;
        $pi->save();
    
        return redirect()->route('proforma.invoice.list')->with('success', 'PI Generated Successfully!');
    }
}
