<?php

namespace App\Http\Controllers;

use App\Models\Branches;
use App\Models\RmdNotes;
use App\Models\Sales;
use App\Models\SalesDetails;
use App\Models\Stock1;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SalesController extends Controller
{

    public function index()
    {
        $branches = Branches::where('branch_id', '!=', session('branch_id'))->orderBy('branch_id', 'ASC')->get();
        return view('sales.index', ['branches' => $branches]);
    }

    public function search_prd(Request $request)
    {
        // $tableName = 'stock_'.$this->session->branch_id;
        // $stk_price = 'stk_sprice_b'.$this->session->branch_id;
        $dynData = session('branch_id'); // Default to 1 if branch_id is not set
        $tableName = 'stock_' . $dynData;
        $stk_price = 'stk_sprice_b' . $dynData;
        $return_arr = array();
        $stk_item = $_GET['term'];
        $query = DB::table($tableName)->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_price . '+' . $rows->stk_name . '+' . $rows->stk_barcode;
                $row_array['value'] = $rows->$stk_price . '+' . $rows->stk_name . '+' . $rows->stk_barcode;
                $row_array['stk_qty'] = $rows->stk_qty;
                array_push($return_arr, $row_array);
                // $return_arr[]=$rows->stk_name.'+'.$rows->stk_barcode;
            }
        }
        echo json_encode($return_arr);
    }

    public function add_items_to_list(Request $request)
    {
        $branch_id = session('branch_id');
        $tableName = 'stock_' . $branch_id;
        $prd_stk     = $request->prd_stk;
        $prd_stk_qty = $request->prd_stk_qty;
        $stk_barcode = explode('+', $prd_stk);
        $stk_barcode = end($stk_barcode);
        $qty = 'yes';
        $stk_qty = 0;
        $q = DB::table($tableName)->where('stk_barcode', $stk_barcode)->first();
        if ($q) {
            $stk_price = 'stk_sprice_b' . $branch_id;
            $sprice = $q->$stk_price;
            $stk_name = $q->stk_name;
            $pprice = $q->stk_pprice;
            $stk_qty = $q->stk_qty;
            if ($prd_stk_qty > $stk_qty) {
                $qty = 'no';
            }
        } else {
            $sprice = 'no';
            $stk_name = 'no';
        }
        echo json_encode(['sprice' => $sprice, 'stk_name' => $stk_name, 'pprice' => $pprice, 'qty' => $qty, 'stk_qty' => $stk_qty, 'stk_barcode' => $stk_barcode]);
    }

    public function process_items(Request $request)
    {
        $branch_id = session('branch_id');
        $tableName             = 'stock_' . $branch_id;
        $type                = $request->type;
        $purchases            = $request->purchases;
        $sub_total           = $request->subtotal;
        $discount            = $request->discount;
        $grand_total         = $request->grandtotal;
        $payments            = $request->payments;
        $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);
        $item_discount      = json_decode($request->item_discount);
        $item_ftotal        = json_decode($request->item_ftotal);
        $invoice = $this->generate_invoice();
        $msg_itm = null;
        $msg = null;
        $customer_id = 0;
        $ins_array = [
            'branch_id' => $branch_id,
            'invoice' => $invoice,
            'type' => $type,
            'customer_id' => $customer_id,
            'purchases' => $purchases,
            'sub_total' => $sub_total,
            'discount' => $discount,
            'grand_total' => $grand_total,
            'payments' => $payments,
            'dated' => now()
        ];
        $ins_query = Sales::create($ins_array);
        if ($ins_query) {
            for ($i = 0; $i < count($item_name); $i++) {
                $exp = explode('+', $item_name[$i]);
                $stk_barcode = end($exp);

                $ins_array = ['branch_id' => $branch_id, 'invoice' => $invoice, 'item_barcode' => $stk_barcode, 'item_name' => $item_name[$i], 'item_pprice' => 0, 'item_price' => $item_price[$i], 'item_qty' => $item_qty[$i], 'item_total' => $item_total[$i], 'item_discount' => $item_discount[$i], 'item_ftotal' => $item_ftotal[$i], 'dated' => now()];
                $ins_query = SalesDetails::create($ins_array);

                $qstk = DB::table($tableName)->where('stk_barcode', $stk_barcode)->first();
                if ($qstk) {
                    $qrow = $qstk;
                    $stk_notify = $qrow->stk_notify;
                    $stk_name  = $qrow->stk_name;
                    $old_qty = $qrow->stk_qty;
                    $new_qty = ($old_qty - $item_qty[$i]);
                    $up_array = ['stk_qty' => $new_qty, 'dated' => now()];
                    DB::table($tableName)->where('stk_barcode', $stk_barcode)->update($up_array);
                }
            }
            if ($ins_query) {
                $msg_itm = 1;
            } else {
                $msg_itm = 0;
            }
        } else {
            $msg = 0;
        }
        if ($msg_itm != 0) {
            $msg = 1;
        } else {
            $msg = 0;
        }
        echo json_encode([$msg, $invoice]);
    }

    public function invoice($invoice)
    {
        $sales = Sales::with('salesDetails')->where('invoice', $invoice)->first();
        if (!$sales) {
            return 'Invoice not found';
        }

        $data = ['dated' => $sales->dated, 'invoice' => $sales->invoice, 'sales_details' => $sales->salesDetails, 'sub_total' => $sales->sub_total, 'discount' => $sales->discount, 'grand_total' => $sales->grand_total, 'payments' => $sales->payments];
        return view('admin.sales_invoice', $data);
    }

    public function show_stock_items()
    {
        $branch_id = session('branch_id');

        $response = [];

        // Get all branches except current one
        $otherBranches = Branches::where('branch_id', '!=', $branch_id)
            ->orderBy('branch_id', 'ASC')
            ->pluck('branch_id');

        $modelClass = 'App\\Models\\Stock' . $branch_id;
        $sno = 0;
        $query = $modelClass::with('category')->orderBy('dated', 'DESC')->get();
        if ($query->count() > 0) {
            $json = [];
            // Preload quantities from other branches in one query per branch
            $otherBranchQuantities = [];
            foreach ($otherBranches as $otherBranchId) {
                $mc = 'App\\Models\\Stock' . $otherBranchId;
                $quantities = $mc::whereIn('stk_barcode', $query->pluck('stk_barcode'))->pluck('stk_qty', 'stk_barcode');

                $otherBranchQuantities[$otherBranchId] = $quantities;
            }
            foreach ($query as $rows) {
                $sno++;
                $stk_price = 'stk_sprice_b' . $branch_id;
                $array = array(
                    $sno,
                    $rows->category->category_name ?? 'N/A',
                    $rows->stk_barcode,
                    $rows->stk_name,
                    $rows->$stk_price,
                    str_replace(',', '', number_format($rows->stk_qty, 0)),
                );
                // Add quantities from other branches
                foreach ($otherBranches as $otherBranchId) {
                    $array[] = $otherBranchQuantities[$otherBranchId][$rows->stk_barcode] ?? null;
                }
                $json[] = $array;
            }
            $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 quotations()
    {
        return view('sales.quotations');
    }

    public function get_rmd_notes(Request $request)
	{
		$rmd_notes = null;
        $q = RmdNotes::where('uid', 1)->first();
		if($q)
		{
			$rmd_notes = $q->rmd_notes;
		}
		echo $rmd_notes;
	}
	public function save_rmd_notes(Request $request)
	{
		$rmd_notes = $request->rmd_notes;
		$q = RmdNotes::where('uid', 1)->first();
		if($q)
		{
			$q->rmd_notes = $rmd_notes;
			if($q->save())
            {
                echo 1;
            }
			else
			{
				echo 0;
			}
		}
		else
		{
			$ins_array = ['rmd_notes'=>$rmd_notes];
			$ins_query = RmdNotes::create($ins_array);
			if($ins_query)
			{
				echo 1;
			}
			else
			{
				echo 0;
			}
		}
	}

    public function last_invoice()
 	{
        $branch_id = session('branch_id');
        $table_itm =null;
 		$customer_name =null;
 		$customer_contact =null;
 		$subtotal = '0.000';
 		$discount = '0.000';
 		$grandtotal = '0.000';
 		$advance = '0.000';
 		$payment = '0.000';
        $q = Sales::with('salesDetails')->where('branch_id', $branch_id)->orderBy('uid','DESC')->first();
 		if($q)
 		{
 			$r = $q;
 			$invoice = $r->invoice;
          	$subtotal = $r->sub_total;
 			$discount = $r->discount;
 			$grandtotal = $r->grand_total;
 			$payment = $r->payments;
 			$branch_id = $r->branch_id;
 			$dated   = $r->dated;
            $totals_itm=0;
            $sno =0;

            foreach($r->salesDetails as $rows)
            {
                $sno++;
                $table_itm .='<tr>
                            <td>'.$sno.' - </td>
                            <td>'.str_replace('+','<br>',$rows->item_name).'</td>
                            <td style="text-align:center;">'.$rows->item_price.'</td>
                            <td style="text-align:center;">'.$rows->item_qty.'</td>
                            <td style="text-align:right;">'.$rows->item_total.'</td>
                            <td style="text-align:right;">'.$rows->item_discount.'</td>
                            <td style="text-align:right;">'.$rows->item_ftotal.'</td>
                            </tr>';
                $totals_itm +=$rows->item_total;
            }
 			$data['invoice'] 			= $invoice;
 			$data['table_itm']			= $table_itm;
 			$data['totals_itm']			= $totals_itm;
 			$data['subtotal'] 			= $subtotal;
 			$data['discount'] 			= $discount;
 			$data['grandtotal'] 		= $grandtotal;
 			$data['payment'] 			= $payment;
 			$data['dated']   			= $dated;
 			$data['branch_id']          = $branch_id;
			return view('sales.invoice',$data);
 		}
 		else
 		{
 			echo 'NO RESULTS FOUND';
 		}
 	}

    private function generate_invoice()
    {

        $id = 0;
        $invoice = 0;
        $date = date('m/Y');
        $query = Sales::select('uid', 'branch_id', 'invoice')
            ->where('branch_id', session('branch_id'))
            ->orderBy('uid', 'desc')
            ->first();
        if ($query) {
            $r = $query;
            $exp = explode('-', $r->invoice);
            $invoice = (end($exp) + 1);
            $invoice = 'INVOICE' . session('branch_id') . ' - ' . $invoice;
        } else {
            $invoice = 'INVOICE' . session('branch_id') . '-00001';
        }
        return $invoice;
    }
}
