<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller as Controller;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use App\Models\Sale;
use App\Models\Saleitems;
use App\Models\Payment;
use PDF;

class SalelistController extends Controller
{
    public function __construct() {
        //parent::__construct();
        //$this->middleware('permission:sale');
    }

    public function index(){
        
        return View('Salelist.index');
    }

    public function ajaxList(Request $request, Sale $saleObj){
        $limit = (int)$request->iDisplayLength;
        $offset = (int)$request->iDisplayStart;

        $searchContents['freetext'] = (string)$request->sSearch;
        if ($request->iSortCol_0 != '') {
            for ($i = 0; $i < $request->iSortingCols; $i++) {
                $iSortCol_ = 'iSortCol_' . $i;
                $sSortDir_ = 'sSortDir_' . $i;
                $sortcol = $request->$iSortCol_;
                $sort[$sortcol] = $request->$sSortDir_;
            }
        } else {
            $sort = null;
        }

        $saleCount = $saleObj->getAllSale($searchContents);
        $saleData = $saleObj->getAllSale($searchContents, $sort, $limit, $offset);

        $rows = array();
        $iDisplayStart = $request->iDisplayStart;

        $i=1;
        foreach ($saleData as $key => $content) {
            $action = '<div class="dropdown">
                <a href="javascript:void(0)" role="button" id="dropdownMenuLink1" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="ri-more-2-fill"></i>
                </a>

                <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                <li><a class="dropdown-item" href="'.route('saleslist.view', ['id' => $content->id]).'">View</a></li>               
                <li><a class="dropdown-item" href="'.route('saleslist.invoice', ['id' => $content->id]).'">GenerateInvoice</a></li>
                <li><a class="dropdown-item payment_add" href="javascript:void(0)" data-id="' . $content->id . '">Add Payment</a></li>
                <li><a class="dropdown-item payment_view" href="javascript:void(0)" data-id="' . $content->id . '">View Payment</a></li>
                </ul>
            </div>';

            if ( $content->dueamount  == '0') {
                $isActive = '<a href="javascript:void(0)" data-id="' . $content->id . '" class="sale_active tooltipped" data-position="top" title="Paid"><i class="ri-checkbox-circle-line align-middle text-success fs-16"></i></a>';
            } else {
                $isActive = '<a href="javascript:void(0)" data-id="' . $content->id . '" class="sale_inactive tooltipped" data-position="top" title="Due"><i class="ri-checkbox-circle-line align-middle text-danger fs-16"></i></a>';
            }
            
            $rowData = array(
                ($limit * $offset/$limit) + $i,
                date("d-m-Y H:i:s",strtotime($content->created_at)),
                $content->invoiceno,
                $content->customername,
                $content->totalamount,
                $content->dueamount,
                $isActive,
                $action
            );
            $rows[] = $rowData;
            $i++;
        }

        $json = array(
            'sEcho' => intval($request->sEcho),
            'iTotalRecords' => $saleCount,
            'iTotalDisplayRecords' => $saleCount,
            'aaData' => $rows
        );

        echo json_encode($json);
    }

    public function invoice($id){
        
        $data = Sale::where('id',$id)->first(); 
        $sale = Saleitems::where('salesid',$id)->get();
        view()->share('Salelist/pdf',$data,$sale);
        $pdf = PDF::loadView('Salelist/pdf',array('data'=>$data,'sale'=>$sale))->setPaper('a3');
        $filename =  "Invoice" .$data->invoiceno;
        return $pdf->stream($filename . '.pdf');
    }

     
    public function view($id){
        $data = Sale::where('id',$id)->first(); 
        $sale = Saleitems::where('salesid',$id)->get();
        return view('Salelist.view',compact('data','sale'));
    }

    

    public function paymentdata(Request $request){
        $data = Sale::where('id',$request->id)->first(); 
        return response()->json($data);
    }

    public function paymentview(Request $request){
        
        $data = Sale::where('id',$request->id)->first();
        return response()->json($data);
    }

    public function paymenttabale(Request $request){
        
        $data = Payment::where('saleid',$request->id)->get();
        return View('Salelist.payment',compact('data'));
    }

    public function payment(Request $request){
        
        $data = Sale::where('id',$request->paymentid)->first(); 
        $totalamount  = $data->totalamount;
        $dueamount = $data->dueamount;
      
        $paymentObj = new Payment();
        $paymentObj->paymenttype = $request->paymenttype;
        $paymentObj->saleid = $request->paymentid;
        $paymentObj->paidamount = $request->duepaidamount;
        $paymentObj->save();

        $saleObj = Sale::where('id',$request->paymentid)->first();
        $saleObj->dueamount = ($dueamount-$request->duepaidamount);
        $saleObj->save();
 
        return redirect()->route('saleslist')->with('success', 'Payment added successfully.');
    }

    public function dueamount(Request $request){
         $valid = TRUE;
        $data = Sale::where('id',$request->paymentid)->first();
        $dueamount = $data->dueamount;
        $duepaidamount = $request->duepaidamount; 
        if($duepaidamount >= $dueamount ){
            $valid = FALSE;
        }
        else {
            $valid = TRUE;
        }

        return json_encode(array('valid' => $valid));
    }

}  