<?php

namespace App\Http\Controllers;

use App\Models\Branches;
use App\Models\Notifications;
use App\Models\StockItems;
use App\Models\StockOut;
use App\Models\TransferDetails;
use App\Models\TransferInvoices;
use App\Models\Transfers;
use Illuminate\Http\Request;

class StockTransferController extends Controller
{

    public function index()
    {
        $data['branches'] = Branches::all();
        return view('admin.stock_transfer', $data);
    }
    public function show()
    {
        $sno = 0;
        $query = Transfers::with(['branchFrom', 'branchTo'])->orderBy('uid', 'DESC')->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {

                $branch_id_from = $rows->branch_id_from == 0 ? 'Admin' : $rows->branchFrom->branch_name;
                $branch_id_to   = $rows->branch_id == 0 ?     'Admin' : $rows->branchTo->branch_name;
                $sno++;
                $json[] = array(
                    $sno,
                    '<a href="#" id="' . $rows->invoice . '" data-toggle="modal" data-target="#trf-details">' . $rows->invoice . '</a>',
                    $branch_id_from,
                    $branch_id_to,
                    $rows->total_items,
                    $rows->dated,
                    '<a href="'.route('stock.transfer.invoice', ['id'=>$rows->invoice]).'" class="" target="_blank"><i class="fa fa-print text-info"></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 add_items_to_transfer_list(Request $request)
    {
        $prd_stk         = $request->prd_stk;
        $prd_stk_qty    = $request->prd_stk_qty;
        $total_branches = $request->total_branches;
        $select_from    = $request->select_from;
        if ($total_branches != 0) {
            $ttype = 'admin';
            $qty_required     = ($prd_stk_qty * $total_branches);
            $stk_barcode = explode('+', $prd_stk);
            $stk_barcode = end($stk_barcode);
            $q = StockItems::where('stk_barcode', $stk_barcode)->first();
            if ($q) {
                $r = $q;
                $sprice = $r->stk_pprice;
                $stk_name = $r->stk_name;
                $stk_qty  = $r->stk_qty;
                if ($qty_required > $stk_qty) {
                    $qty_avl = 'no';
                } else {
                    $qty_avl = 'yes';
                }
            } else {
                $sprice = 'no';
                $stk_name = 'no';
                $stk_qty = 'no';
                $qty_avl = 'no';
                $qty_required = 'no';
            }
        } else if ($select_from != "") {
            $ttype = 'inter';
            $qty_required = $prd_stk_qty;
            $stk_barcode = explode('+', $prd_stk);
            $stk_barcode = end($stk_barcode);
            $table = 'stock_' . $select_from;
            $q = $table::where('stk_barcode', $stk_barcode)->first();
            if ($q) {
                $r = $q;
                $sprice = $r->stk_pprice;
                $stk_name = $r->stk_name;
                $stk_qty  = $r->stk_qty;
                if ($qty_required > $stk_qty) {
                    $qty_avl = 'no';
                } else {
                    $qty_avl = 'yes';
                }
            } else {
                $sprice = 'no';
                $stk_name = 'no';
                $stk_qty = 'no';
                $qty_avl = 'no';
                $qty_required = 'no';
            }
        }
        echo json_encode(array(
            'sprice' => $sprice,
            'stk_name' => $stk_name,
            'qty_avl' => $qty_avl,
            'stk_qty' => $stk_qty,
            'qty_required' => $qty_required,
            'ttype' => $ttype
        ));
    }

    public function process_transfer_items(Request $request)
    {
        $sub_total   = $request->subtotal;
        $ttype        = $request->ttype;
        $select_from = $request->select_from;
        $select_to   = $request->select_to;
        $branches    = json_decode($request->branches);
        $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);
        $trfarr      = array();
        if ($ttype == 'inter') {
            $invoice =$this->generate_transfer();
            $msg = null;
            
            $ins_array = [
                'invoice' => $invoice,
                'branch_id_from' => $select_from,
                'branch_id' => $select_to,
                'sub_total' => $sub_total,
                'total_items' => count($item_name),
                'logedin_user' => null,
                'dated' => now()
            ];
            $ins_query = Transfers::create($ins_array);
            if ($ins_query) {
                array_push($trfarr, $invoice);
                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 = TransferDetails::create($ins_array);
                    $exp = explode('+', $item_name[$i]);
                    $stk_barcode = end($exp);
                    $table = 'stock_' . $select_from;
                    $qstk = $table::where('stk_barcode', $stk_barcode)->first();
                    if ($qstk) {
                        $price_branch_1 = StockItems::where('stk_barcode', $stk_barcode)->value('stk_sprice_b1')??0;
                        $price_branch_2 = StockItems::where('stk_barcode', $stk_barcode)->value('stk_sprice_b2')??0;
                        $price_branch_3 = StockItems::where('stk_barcode', $stk_barcode)->value('stk_sprice_b3')??0;
                        $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, 'stk_sprice_b1' => $price_branch_1, 'stk_sprice_b2' => $price_branch_2, 'stk_sprice_b3' => $price_branch_3, 'dated' => now()];
                        $table = 'stock_' . $select_from;
                        $up_query = $table::where('stk_barcode', $stk_barcode)->update($up_array);
                        if ($up_query) {
                            $ins_array = [
                                'branch_id' => $select_from,
                                'stk_item' => $stk_barcode,
                                'stk_quantity' => $item_qty[$i],
                                'reason' => 'Transfer',
                                'dated' => now()
                            ];
                            $ins_query = StockOut::create($ins_array);
                            if ($ins_query) {
                                if ($select_to != 0) {
                                    $table = 'stock_' . $select_to;
                                } else {
                                    $table = 'stock_items';
                                }
                                //REVIEW
                                if (!$this->db->table_exists($table)) {
                                    $this->db->query("CREATE TABLE  $table LIKE stock_items");
                                }
                                $q = $table::where('stk_barcode', $stk_barcode)->first();
                                if ($q) {
                                    $r = $q;
                                    $old_qty = $r->stk_qty;
                                    $new_qty = ($old_qty + $item_qty[$i]);
                                    $up_array = ['stk_qty' => $new_qty, 'dated' => now()];
                                    $up_query = $table::where('stk_barcode', $stk_barcode)->update($up_array);
                                } else {
                                    $table='stock_' . $select_from;
                                    $nq = $table::where('stk_barcode', $stk_barcode)->first();
                                    if ($nq) {
                                        $nr = $nq;
                                        $ins_array = array(
                                            'stk_category' => $nr->stk_category,
                                            'stk_barcode' => $nr->stk_barcode,
                                            'stk_name' => $nr->stk_name,
                                            'stk_pprice' => $nr->stk_pprice,
                                            'stk_pdate' => $nr->stk_pdate,
                                            'stk_provider' => $nr->stk_provider,
                                            'stk_sprice_b1' => $nr->stk_sprice_b1,
                                            'stk_sprice_b2' => $nr->stk_sprice_b2,
                                            'stk_sprice_b3' => $nr->stk_sprice_b3,
                                            'stk_qty' => $item_qty[$i],
                                            'stk_notify' => $nr->stk_notify,
                                            'stk_notes' => $nr->stk_notes,
                                            'in_user' =>null,
                                            'dated' => now()
                                        );
                                        $table::create($ins_array);
                                    }
                                }

                                // if($new_qty<=$stk_notify)
                                // {
                                // 	$ins_array = array('notify_type'=>'STOCK ITEMS','notify_text'=>$stk_name.' is running out','dated'=>timestamp);
                                // 	$this->db->insert('notifications',$ins_array);
                                // }
                            }
                        }
                    }
                }
                if ($ins_query > 0) {
                    $msg = 1;
                } else {
                    $msg = 0;
                }
            } else {
                $msg = 0;
            }
        }
        if ($ttype == 'admin') {
            for ($x = 0; $x < count($branches); $x++) {
                $invoice = $this->generate_transfer();
                $msg = null;
                $ins_array = [
                    'invoice' => $invoice,
                    'branch_id' => $branches[$x],
                    'sub_total' => $sub_total,
                    'total_items' => count($item_name),
                    'logedin_user' => null,
                    'dated' => now()
                ];
                $ins_query = Transfers::create($ins_array);
                if ($ins_query) {
                    array_push($trfarr, $invoice);
                    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 = TransferDetails::create($ins_array);
                        $exp = explode('+', $item_name[$i]);
                        $stk_barcode = end($exp);
                        $qstk = StockItems::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()
                            ];
                            $up_query = StockItems::where('stk_barcode', $stk_barcode)->update($up_array);
                            if ($up_query) {
                                $ins_array = [
                                    'stk_item' => $stk_barcode,
                                    'stk_quantity' => $item_qty[$i],
                                    'reason' => 'Transfer',
                                    'dated' => now()
                                ];
                                $ins_query = StockOut::create($ins_array);
                                if ($ins_query) {
                                    $table = 'stock_' . $branches[$x];
                                    //REVEIW
                                    if (!$this->db->table_exists($table)) {
                                        $this->db->query("CREATE TABLE  $table LIKE stock_items");
                                    }
                                    $q = $table::where('stk_barcode', $stk_barcode)->first();
                                    if ($q) {
                                        $r = $q;
                                        $old_qty = $r->stk_qty;
                                        $new_qty = ($old_qty + $item_qty[$i]);
                                        $up_array = ['stk_qty' => $new_qty, 'dated' => now()];
                                        $table::where('stk_barcode', $stk_barcode)->update($up_array);
                                    } else {
                                        $nq = StockItems::where('stk_barcode', $stk_barcode)->first();
                                        if ($nq) {
                                            $nr = $nq;
                                            $ins_array = [
                                                'stk_category' => $nr->stk_category,
                                                'stk_barcode' => $nr->stk_barcode,
                                                'stk_name' => $nr->stk_name,
                                                'stk_pprice' => $nr->stk_pprice,
                                                'stk_pdate' => $nr->stk_pdate,
                                                'stk_provider' => $nr->stk_provider,
                                                'stk_sprice_b1' => $nr->stk_sprice_b1,
                                                'stk_sprice_b2' => $nr->stk_sprice_b2,
                                                'stk_sprice_b3' => $nr->stk_sprice_b3,
                                                'stk_qty' => $item_qty[$i],
                                                'stk_notify' => $nr->stk_notify,
                                                'stk_notes' => $nr->stk_notes,
                                                'in_user' => null,
                                                'dated' => now()
                                            ];
                                            
                                            $table::create($ins_array);
                                        }
                                    }

                                    if ($new_qty <= $stk_notify) {
                                        $ins_array = ['notify_type' => 'STOCK ITEMS', 'notify_text' => $stk_name . ' is running out', 'dated' => now()];
                                        
                                        Notifications::create($ins_array);
                                    }

                                }
                            }
                        }
                    }
                    if ($ins_query > 0) {
                        $msg = 1;
                    } else {
                        $msg = 0;
                    }
                } else {
                    $msg = 0;
                }
            }
        }
        echo json_encode(array($msg, $trfarr));
    }

    public function details(Request $request)
    {
        $invoice     = $request->invoice;
        $q = TransferDetails::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>' . $total_sprice . '</td>
 			    				  	</tr>
 			    				  </tfoot>
 		    				  </table>';
        } else {
            $table = 'NO DATA TO DISPLAY';
        }
        echo json_encode([$table]);
    }

    public function invoice($invoice)
    {
        $query = TransferDetails::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 = Transfers::where('invoice',$invoice)->first();
            if ($q) {
                $r = $q;
                $branch_id_from = $r->branch_id_from;
                $branch_id = $r->branch_id;
                $total_items = $r->total_items;
                $dated   = date('d/m/Y', strtotime($r->dated));
            }
            $data['user'] = Transfers::where('invoice', $invoice)->value('logedin_user')??null;
            $data['invoice'] = $invoice;
            $data['table'] = $table;
            $data['totals'] = $totals;
            $data['total_items'] = $total_items;
            $data['branch_from'] = $this->getBranch($branch_id_from);
            $data['branch_to'] = $this->getBranch($branch_id);
            if ($branch_id_from == 0) {
                $data['branch_from'] = 'Admin';
            }
            if ($branch_id == 0) {
                $data['branch_to'] = 'Admin';
            }
            $data['dated']   = $dated;
            return view('admin.stock_transfer_invoice', $data);
        } else {
            echo 'NO RESULTS FOUND';
        }
    }

    private function getBranch($branch_id)
    {
        $b = Branches::where('branch_id', $branch_id)->first();
        if ($b) {
            return $b->branch_name;
        } else {
            return 'Unknown Branch';
        }
    }
    private function generate_transfer()
    {
        $id = 0;
        $invoice = 0;
        $date = date('m/Y');
        $query = TransferDetails::orderBy('invoice_uid','DESC')->limit(1)->get();
        if ($query->count() == 1) {
            foreach ($query as $rows) {
                $id = $rows->invoice_uid;
            }
            $invoice = $id + 1;
            $invoice = 'TRF-00' . $invoice;
        } else {
            $invoice = 'TRF-001';
        }
        $insdata = ['invoice_number' => $invoice];
        $insquery = TransferInvoices::create($insdata);
        if ($insquery) {
            $ci->db->order_by('invoice_uid', 'desc');
            $ci->db->limit(1);
            $query = $ci->db->get('transfer_invoices');
            $query = TransferInvoices::orderBy('invoice_uid','DESC')->limit(1)->get();
            if ($query->count() == 1) {
                foreach ($query as $rows) {
                    $invoice = $rows->invoice_number;
                }
            }
            return $invoice;
        } else {
            return 'err';
        }
    }
}
