<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Purchase;
use Auth;
use App\Models\Transaction;
use App\Models\PurchaseLine;
use App\Models\Stock;
use App\Models\SellLines;
use Illuminate\Support\Facades\Validator;
use DB;
class PurchaseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('add-purchase');
    }
    public function manage_purchase(){
        return view('manage-purchase');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
        'date' => 'required',
        'supplier_name' => 'required',
        'voucher_no' => 'required',
        'qty' => 'required',
        'price' => 'required',
        'tax' => 'required',
        'final_amount' => 'required'
        ]);

        if ($validator->fails()) {
        return redirect('PurchaseController@index')
                 ->withErrors($validator)
                 ->withInput();
        }else{
            try {
                $data = request()->all();
                // print_r($data);die;
                $data['created_by']=Auth::user()->id;
                $data['transaction_date']=$request->date;
                $data['supplier_name']=$request->supplier_name;
                $data['voucher_no']=$request->voucher_no;
                $data['amount']=$request->final_amount;
                $data['type']='purchase';
                $data['payment_mode']='cash';
                $insert=Transaction::create($data);
                $purchase_lines=array('transaction_id'=>$insert->id,'qty'=>$request->qty,
                    'price'=>$request->price,'tax'=>$request->tax,'final_amount'=>$request->final_amount,'delivery_no'=>$request->delivery_no,'invoice_no'=>$request->invoice_no);
                $insert_purchase_data=PurchaseLine::create($purchase_lines);
                $this->Update_qty();

                if($insert_purchase_data){
                    return redirect('manage-purchase')->with('success','Successfully Submitted');
                }
            } catch (\Throwable $th) {
                return $th->getMessage();
            }

        }
    }

    function fetch_purchase_data(Request $request){
        
        $result = array('data' => array());
        $report=Transaction::select('transaction.supplier_name','transaction.transaction_date','transaction.voucher_no','transaction.id','users.name as user_name','purchase_lines.qty','purchase_lines.price','purchase_lines.tax','purchase_lines.final_amount','purchase_lines.delivery_no','purchase_lines.invoice_no')
                            ->leftjoin('users','users.id','=','transaction.created_by')
                            ->leftjoin('purchase_lines','purchase_lines.transaction_id','=','transaction.id')
                            ->where('transaction.type','=','purchase')
                            ->orderBy('transaction.id', 'DESC');


        if(!empty($request->datefrom)){
         $datefrom=date('Y-m-d',strtotime($request->datefrom));

         $report->whereDate('transaction.transaction_date', '>=', $datefrom);

        }
        if (!empty($request->dateto)) {
            $dateto=date('Y-m-d',strtotime($request->dateto));
            $report->whereDate('transaction.transaction_date', '<=', $dateto);
        }
        
        

        $data=$report->get();

         $i=1;
         foreach ($data as $key => $value) {
            
            $button='';
        
            $button='<td>
                    <a  class="btn bg-gradient-info btn-sm"  href="'.url('edit-purchase/'.$value['id']).'">Edit</a></td>';
                if (auth()->user()->role == 'admin' ) {
                $button.='<td> <a type="button" class="btn bg-gradient-danger btn-sm" data-id="'.$value['id'].'" id="delete">Delete</a></td>';
            }
            


                $result['data'][$key] = array(
                $i,
                $value['transaction_date'],
                $value['supplier_name'],
                $value['delivery_no'],
                $value['invoice_no'],
                $value['voucher_no'],
                $value['qty'],
                $value['price'],
                $value['tax'],
                $value['final_amount'],
                $value['user_name'],
                $button,
            );
       $i++;  }
     echo json_encode($result);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data=Transaction::select('transaction.supplier_name','transaction.transaction_date','transaction.voucher_no','transaction.id','purchase_lines.qty','purchase_lines.price','purchase_lines.tax','purchase_lines.final_amount','purchase_lines.delivery_no','purchase_lines.invoice_no')->leftjoin('purchase_lines','purchase_lines.transaction_id','=','transaction.id')
                            ->where('transaction.id','=',$id)->first();
                            // print_r($data);die;
        return view('edit-purchase',compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
        'date' => 'required',
        'supplier_name' => 'required',
        'voucher_no' => 'required',
        'qty' => 'required',
        'price' => 'required',
        'tax' => 'required',
        'final_amount' => 'required'
        ]);

        if ($validator->fails()) {
        return redirect('edit-purchase/'.$id)
                 ->withErrors($validator)
                 ->withInput();
        }else{
            try {
                // print_r($request->all());die;
                 $update=Transaction::find($id);
                // echo $update->created_by;die;
                $update->created_by=Auth::user()->id;
                $update->transaction_date=$request->date;
                $update->supplier_name=$request->supplier_name;
                $update->voucher_no=$request->voucher_no;
                $update->amount=$request->final_amount;
                $update->type='purchase';
                $update->payment_mode='cash';
                $update->save();
                $delete = PurchaseLine::where('transaction_id','=',$id);
                $delete->delete();
                $purchase_lines=array('transaction_id'=>$id,'qty'=>$request->qty,
                    'price'=>$request->price,'tax'=>$request->tax,'final_amount'=>$request->final_amount,'delivery_no'=>$request->delivery_no,'invoice_no'=>$request->invoice_no);
                $insert_purchase_data=PurchaseLine::create($purchase_lines);
                $this->Update_qty();
                if($insert_purchase_data){
                    return redirect('manage-purchase')->with('success','Successfully Submitted');
                }
            } catch (\Throwable $th) {
                return $th->getMessage();
            }

        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $Transaction = Transaction::find($id);
        $Transaction->delete();
        $PurchaseLine = PurchaseLine::where('transaction_id','=',$id);
        $PurchaseLine->delete();
        $this->Update_qty();
    }

    function purchase_report(){
        return view('purchase-report');
    }
    function fetchPurchaseReport(Request $request){
        $result = array('data' => array());
        $report=Transaction::select('transaction.supplier_name','transaction.transaction_date','transaction.voucher_no','transaction.id','users.name as user_name','purchase_lines.qty','purchase_lines.price','purchase_lines.tax','purchase_lines.final_amount','purchase_lines.delivery_no','purchase_lines.invoice_no')
                            ->leftjoin('users','users.id','=','transaction.created_by')
                            ->leftjoin('purchase_lines','purchase_lines.transaction_id','=','transaction.id')->where('transaction.type','=','purchase')
                            ->orderBy('purchase_lines.transaction_id', 'DESC');


        if(!empty($request->datefrom)){
         $datefrom=date('Y-m-d',strtotime($request->datefrom));

         $report->whereDate('transaction.transaction_date', '>=', $datefrom);

        }
        if (!empty($request->dateto)) {
            $dateto=date('Y-m-d',strtotime($request->dateto));
            $report->whereDate('transaction.transaction_date', '<=', $dateto);
        }
        
        

        $data=$report->get();

         $i=1;
         foreach ($data as $key => $value) {
     


                $result['data'][$key] = array(
                $i,
                $value['transaction_date'],
                $value['supplier_name'],
                $value['delivery_no'],
                $value['invoice_no'],
                $value['voucher_no'],
                $value['qty'],
                $value['price'],
                $value['tax'],
                $value['final_amount'],
                $value['user_name'],
              
            );
       $i++;  }
     echo json_encode($result);
    }
     function Update_qty(){
       $id=1;
       $stock= Stock::find($id);
        $total_sale_stock = SellLines::sum('quantity');
        $total_purchase_stock = PurchaseLine::sum('qty');
        $total_return_stock = SellLines::sum('return_qty');
        $new_stock= ($total_purchase_stock + $total_return_stock) - $total_sale_stock;
    //   $old_qty=$stock->stock;
    //   $total_sale_stock=SellLines::sum('quantity');
    //   $total_purchase_stock=PurchaseLine::sum('qty');
      $stock->stock=$new_stock;
       // echo $total_purchase_stock - $total_sale_stock;die;
       $stock->is_refreshed=0;
       $stock->save();
 
    }
  function stock_report(){
        return view('stock-report');
    }
function fetch_stock_report(){
    $result = array('data' => array());
    $report=Stock::all();
         $i=1;
         foreach ($report as $key => $value) {
                     $button = '';
                     if($value['id'] == 1|| $value['id'] == 3){
                         if($value['is_refreshed'] == 0){
                             $button .= '<td>  <a  class="btn bg-gradient-info btn-sm" data-id="' . $value['id'] . '" id="refresh">Refresh</a>';
                         }
                         
                     }
            
            //  $button .= '  <a type="button" class="btn bg-gradient-danger btn-sm" data-id="' . $value['id'] . '" id="delete">Delete</a>  </td>';
         $result['data'][$key] = array(
                $i,
                $value['item'],
                round($value['stock'],2),
                $button
              
            );
       $i++;  }
     echo json_encode($result);
}
    function refresh($id){
        
        $total_return_stock=0;
        $total_purchase_stock=0;
        $total_sale_stock=0;
        $new_stock='';
       
        $total_sale_stock = SellLines::sum('quantity');
        $total_purchase_stock = PurchaseLine::sum('qty');
        $total_return_stock = SellLines::sum('return_qty');
        $new_stock= ($total_purchase_stock + $total_return_stock) - $total_sale_stock;
     
        
        if($id == 1){
            $stock = Stock::find($id);
            $stock->stock=$new_stock;
            $stock->is_refreshed=1;
            $stock->save();
        }
         if($id == 3){
            $stock = Stock::find($id);
            $stock->stock = $stock->last_meter+$total_sale_stock;
            $stock->is_refreshed=1;
            $stock->save();
        }
    }
}
