<?php

namespace App\Http\Controllers;

use App\Models\PurchaseDetails;
use App\Models\PurchaseInvoices;
use App\Models\Purchases;
use App\Models\StockIn;
use App\Models\StockItems;
use App\Models\Suppliers;
use Illuminate\Http\Request;

class PurchaseController extends Controller
{
    public function index()
    {
        $data['suppliers'] = Suppliers::all();
        return view('admin.purchases', $data);
    }

    public function show()
    {
        $sno = 0;
        $query = Purchases::with('supplier')->orderBy('dated', 'DESC')->get();
        if ($query->count() > 0) {

            foreach ($query as $rows) {
                $sno++;
                $supplierName = $rows->supplier?->spl_name ?? 'Unknown';
                $supplierContact = $rows->supplier?->spl_contact ?? '';
                $json[] = array(
                    $sno,   
                    '<a href="#" id="' . $rows->invoice . '" data-toggle="modal" data-target="#pinvoice-details">' . $rows->invoice . '</a>',
                    $supplierName. '-' . $supplierContact,
                    $rows->sub_total,
                    $rows->dated,
                    '<a href="'.route('purchases.invoice',['id'=>$rows->invoice]).'" target="_blank" class="mr-2"><i class="fa fa-print text-info"></i></a>' .
                        '<a href="#" data-toggle="modal" data-target="#purchase-edit-modal" id="' . $rows->invoice . '" class="mr-2"><i class="fas fa-edit text-warning"></i></a>' .
                        '<a href="javascript:void(0);" data-uid="' . $rows->invoice . '" class="ifdel"><i class="fa fa-trash text-danger"></i></a>',

                );
            }
            $response = array();
            $response['success'] = true;
            $response['aaData'] = $json;
            echo json_encode($response);
        } else {
            $response = array();
            $response['sEcho'] = 0;
            $response['iTotalRecords'] = 0;
            $response['iTotalDisplayRecords'] = 0;
            $response['aaData'] = [];
            echo json_encode($response);
        }
    }
    public function invoiceDetails(Request $request)
    {
        $invoice     = $request->invoice;
        $q = PurchaseDetails::where('invoice', $invoice)->get();
        if ($q->count() > 0) {
            $sno = 0;
            $total_sprice = 0;
            $total_pprice = 0;
            $table = '<table class="table">
		    				<thead>
		    					<tr>
		    						<th>Sno</th>
		    						<th>Item</th>
		    						<th>Price</th>
		    						<th>Qty</th>
		    						<th>Total</th>
		    					</tr>
		    				</thead>
		    				<tbody>';
            foreach ($q as $r) {
                $sno++;
                $table .= '<tr>
		    					<td>' . $sno . '</td>
		    					<td>' . $r->item_name . '</td>
		    					<td>' . $r->item_price . '</td>
		    					<td>' . $r->item_qty . '</td>
		    					<td>' . $r->item_total . '</td>
		    				  </tr>';
                $total_sprice += $r->item_total;
            }
            $table .= '</tbody>
			    				  <tfoot>
			    				  	<tr>
			    				  		<td>&nbsp;</td>
			    				  		<td>&nbsp;</td>
			    				  		<td>&nbsp;</td>
			    				  		<td>&nbsp;</td>
			    				  		<td>' . formatAmount($total_sprice) . '</td>
			    				  	</tr>
			    				  </tfoot>
		    				  </table>';
        } else {
            $table = 'NO DATA TO DISPLAY';
        }
        echo json_encode([$table]);
    }
    public function invoiceEditDetails(Request $request)
    {
        $invoice     = $request->invoice;
        $q = PurchaseDetails::where('invoice', $invoice)->get();
        if ($q->count() > 0) {
            $sno = 0;
            $total_sprice = 0;
            $total_pprice = 0;
            $table = '<table class="table">
		    				<thead>
		    					<tr>
		    						<th>Sno</th>
		    						<th>Item</th>
		    						<th>Price</th>
		    						<th>Qty</th>
		    						<th>Total</th>
		    					</tr>
		    				</thead>
		    				<tbody>';
            foreach ($q as $r) {
                $sno++;
                $table .= '<tr>
		    					<td>' . $sno . '</td>
		    					<td class="epur-item">' . $r->item_name . '</td>
		    					<td><input type="text" class="form-control epur-price isnumber" style="width:120px;" value="' . $r->item_price . '"></td>
		    					<td><input type="text" class="form-control epur-qty isnumber" style="width:120px;" value="' . $r->item_qty . '"></td>
		    					<td class="epur-total">' . $r->item_total . '</td>
		    				  </tr>';
                $total_sprice += $r->item_total;
            }
            $table .= '</tbody>
			    				  <tfoot>
			    				  	<tr>
			    				  		<td>&nbsp;</td>
			    				  		<td>&nbsp;</td>
			    				  		<td>&nbsp;</td>
			    				  		<td>&nbsp;</td>
			    				  		<td id="epur-gtotal">' . $total_sprice . '</td>
			    				  	</tr>
			    				  </tfoot>
		    				  </table>';
        } else {
            $table = 'NO DATA TO DISPLAY';
        }
        echo json_encode([$table]);
    }
    public function details($invoice)
    {
        $query = PurchaseDetails::where('invoice', $invoice)->get();
        $data['purchases'] = $query;
        $data['invoice'] = $invoice;
        return view('purchase_details', $data);
    }
    public function purchases()
    {
        $query = Suppliers::all();
        $data['suppliers'] = $query;
        return view('purchases', $data);
    }

    public function searchPrd()
    {
        $return_arr = array();
        $stk_item = $_GET['term'];
        $query = StockItems::where('stk_barcode', 'like', $stk_item . '%')
            ->orWhere('stk_name', 'like', $stk_item . '%')
            ->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {
                $row_array['label'] = $rows->stk_name . '+' . $rows->stk_barcode;
                $row_array['value'] = $rows->stk_name . '+' . $rows->stk_barcode;
                $row_array['stk_qty'] = $rows->stk_qty;
                $price = $rows->stk_pprice;
                $q = StockIn::where('stk_item', $rows->stk_barcode)
                    ->orderBy('stk_id', 'DESC')
                    ->limit(1)
                    ->get();
                if ($q->count() == 1) {
                    $r = $q->first();
                    $price = $r->stk_price;
                }

                $row_array['stk_price'] = $price;
                array_push($return_arr, $row_array);
                // $return_arr[]=$rows->stk_name.'+'.$rows->stk_barcode;
            }
        }
        echo json_encode($return_arr);
    }

    public function addItemsToList(Request $request)
    {
        $prd_stk = $request->input('prd_stk');
        $stk_barcode = explode('+', $prd_stk);
        $stk_barcode = end($stk_barcode);
        $query = StockItems::where('stk_barcode', $stk_barcode)->first();
        if ($query) {
            $sprice = $query->stk_pprice;
            $stk_name = $query->stk_name;
        } else {
            $sprice = 'no';
            $stk_name = 'no';
        }
        echo json_encode([$sprice, $stk_name]);
    }

    public function processItems(Request $request)
    {
        $spl         = $request->spl;
        $sub_total   = $request->subtotal;
        $purchase_date = $request->purchase_date;
        $advance     = $request->advance;
        $ptype       = $request->ptype;
        $pcheque     = $request->pcheque;
        $pnotes      = $request->pnotes;
        $item_name   = json_decode($request->item_name);
        $item_price  = json_decode($request->item_price);
        $item_qty    = json_decode($request->item_qty);
        $item_total  = json_decode($request->item_total);
        $invoice = $this->generate_pinvoice();
        $msg = null;
        $ins_array = ['invoice' => $invoice, 'spl_id' => $spl, 'sub_total' => $sub_total, 'advance' => $advance, 'ptype' => $ptype, 'pcheque' => $pcheque, 'pnotes' => $pnotes, 'purchase_date' => $purchase_date, 'dated' => now()];
        $ins_query = Purchases::create($ins_array);
        if ($ins_query) {
            for ($i = 0; $i < count($item_name); $i++) {
                $ins_array = ['invoice' => $invoice, 'item_name' => $item_name[$i], 'item_price' => $item_price[$i], 'item_qty' => $item_qty[$i], 'item_total' => $item_total[$i]];
                $ins_query = PurchaseDetails::create($ins_array);
                $exp = explode('+', $item_name[$i]);
                $stk_barcode = end($exp);
                $qstk = StockItems::where('stk_barcode', $stk_barcode)->first();
                if ($qstk) {
                    $qrow = $qstk;
                    $old_qty = $qrow->stk_qty;
                    $new_qty = ($old_qty + $item_qty[$i]);
                    $up_array = ['stk_qty' => $new_qty, 'stk_pprice' => $item_price[$i], 'dated' => now()];
                    $up_query = StockItems::where('stk_barcode', $stk_barcode)->update($up_array);
                    if ($up_query) {
                        $ins_array = ['stk_item' => $stk_barcode, 'stk_date' => $purchase_date, 'stk_quantity' => $item_qty[$i], 'dated' => now(), 'stk_price' => $item_price[$i]];
                        $ins_query = StockIn::create($ins_array);
                    }
                }
            }
            if ($ins_query) {
                $msg = 1;
            } else {
                $msg = 0;
            }
        } else {
            $msg = 0;
        }
        echo json_encode([$msg, $invoice]);
    }

    public function invoice($invoice)
    {
        $query = PurchaseDetails::where('invoice', $invoice)->get();
        if ($query->count() > 0) {
            $table = null;
            $sno = 0;
            $totals = 0;
            foreach ($query as $rows) {
                $sno++;
                $table .= '<tr>
 	 							<th>' . $sno . '</th>
 	 							<th>' . $rows->item_name . '</th>
 	 							<th>' . $rows->item_price . '</th>
 	 							<th>' . $rows->item_qty . '</th>
 	 							<th>' . $rows->item_total . '</th>
 	 							<th>&nbsp;</th>
 	 						  </tr>';
                $totals += $rows->item_total;
            }
            $q= Purchases::with('supplier')->where('invoice', $invoice)->first();
            if ($q) {
                
                $notes = $q->pnotes;
                // $branch_id = $r->branch_id;
                // $total_items = $r->total_items;
                $supplier_name = $q->supplier->spl_name;
                $supplier_contact =$q->supplier->spl_contact;
                $supplier_email = $q->supplier->spl_email;
                $user = $q->logedin_user;
                $dated   = date('d/m/Y', strtotime($q->dated));
            }
            $data['user'] = $user;
            $data['invoice'] = $invoice;
            $data['table'] = $table;
            $data['totals'] = $totals;
            $data['total_items'] = ''; //$total_items;
            $data['branch'] = ''; //get_column('branches','branch_id',$branch_id,'branch_name');
            $data['supplier_name'] = $supplier_name;
            $data['supplier_contact'] = $supplier_contact;
            $data['supplier_email'] = $supplier_email;
            $data['dated']   = $dated;
            $data['notes'] = $notes;
            return view('admin.purchase_invoice', $data);
        } else {
            echo 'NO RESULTS FOUND';
        }
    }

    public function pur_ac()
    {
        $return_arr = array();
        $stk_item = $_GET['term'];
        $query = StockItems::where('stk_name', 'like', $stk_item . '%')->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {
                $return_arr[] = $rows->stk_name . '+' . $rows->stk_barcode;
            }
        }
        echo json_encode($return_arr);
    }
    public function update(Request $request)
    {
        $invoice    = $request->invoice;
        $sub_total  = $request->sub_total;
        $item_name  = json_decode($request->item_name);
        $item_price = json_decode($request->item_price);
        $item_qty   = json_decode($request->item_qty);
        $query = PurchaseDetails::where('invoice', $invoice)->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {
                $stk_barcode = explode('+', $rows->item_name);
                $stk_barcode = end($stk_barcode);
                $stk_qty     = $rows->item_qty;
                $q = StockItems::where('stk_barcode', $stk_barcode)->first();
                if ($q) {
                    $old_qty = $q->stk_qty;
                }
                $new_qty     = ($old_qty - $stk_qty);
                $up_array = ['stk_qty' => $new_qty];
                StockItems::where('stk_barcode', $stk_barcode)->update($up_array);
            }
            $delPurchase = PurchaseDetails::where('invoice', $invoice)->delete();
            if ($delPurchase) {
                for ($i = 0; $i < count($item_name); $i++) {
                    $ins_array = ['invoice' => $invoice, 'item_name' => $item_name[$i], 'item_price' => $item_price[$i], 'item_qty' => $item_qty[$i], 'item_total' => ($item_qty[$i] * $item_price[$i])];
                    PurchaseDetails::create($ins_array);
                    $stk_barcode = explode('+', $item_name[$i]);
                    $stk_barcode = end($stk_barcode);
                    $stk_qty     = $item_qty[$i];
                    $q = StockItems::where('stk_barcode', $stk_barcode)->first();
                    if ($q) {
                        $old_qty = $q->stk_qty;
                    }
                    $new_qty     = ($old_qty + $stk_qty);
                    $up_array = ['stk_qty' => $new_qty];
                    StockItems::where('stk_barcode', $stk_barcode)->update($up_array);
                }
            }

            $up_array =['sub_total' => $sub_total];
            $up_query = Purchases::where('invoice', $invoice)->update($up_array);
            if ($up_query) {
                $msg = 1;
            } else {
                $msg = 2;
            }
            echo json_encode([$msg]);
        }
    }
    public function getSuppliers()
    {
        $query = Suppliers::all();
        return $query;
    }

    public function delete(Request $request)
    {
        $invoice = $request->invoice;
        $flag1 = 0;
        $flag2 = 0;
        $msg =0;
        $query = PurchaseDetails::where('invoice', $invoice)->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {
                $stk_barcode = explode('+', $rows->item_name);
                $stk_barcode = end($stk_barcode);
                $stk_qty     = $rows->item_qty;
                $q = StockItems::where('stk_barcode', $stk_barcode)->first();
                if ($q) {
                    $old_qty = $q->stk_qty;
                }
                $new_qty     = ($old_qty - $stk_qty);
                $up_array = ['stk_qty' => $new_qty];
                $up_query = StockItems::where('stk_barcode', $stk_barcode)->update($up_array);
            }
        }

        $delPurchase = Purchases::where('invoice', $invoice)->delete();
        if ($delPurchase) {
            $flag1 = 1;
        }
        $delPurchaseDetails = PurchaseDetails::where('invoice', $invoice)->delete();
        if ($delPurchaseDetails) {
            $flag2 = 1;
        }
        // REVIEW
        if ($flag1 != 0 || $flag2 != 0) {
            $msg =1;
        } 
        echo $msg;

    }

    private function generate_pinvoice()
    {
        $id = 0;
        $invoice = 0;
        $date = date('m/Y');
        $invoice = 'PO-001';
        $query = PurchaseInvoices::orderBy('invoice_uid', 'desc')->limit(1)->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {
                $id = $rows->invoice_uid;
            }
            $invoice = $id + 1;
            $invoice = 'PO-00' . $invoice;
        }
        $insdata = ['invoice_number' => $invoice];
        $insquery = PurchaseInvoices::create($insdata);
        if ($insquery) {
            $query = PurchaseInvoices::orderBy('invoice_uid', 'desc')->limit(1)->get();
            if ($query->count() == 1) {
                foreach ($query as $rows) {
                    $invoice = $rows->invoice_number;
                }
            }
            return $invoice;
        } else {
            return 'err';
        }
    }
}
