<?php

namespace App\Http\Controllers;

use App\Models\PurchaseDetails;
use App\Models\PurchasePayments;
use App\Models\Purchases;
use Illuminate\Http\Request;

use App\Models\Suppliers;

class SupplierController extends Controller
{
    public function index()
    {
        return view('admin.suppliers');
    }

    public function show()
    {
        $sno = 0;
        $query = Suppliers::orderBy('dated', 'DESC')->get();
        if ($query->count() > 0) {
            foreach ($query as $rows) {
                $sno++;
                $json[] = array(
                    $sno,
                    $rows->spl_name,
                    $rows->spl_contact,
                    $rows->spl_email,
                    $rows->spl_address,
                    $rows->spl_notes,
                    '<a href="#" data-toggle="modal" data-target="#supplier-invoices-modal" class="text-success" id="' . $rows->spl_id . '" title="Make Payment"><i class="fa fa-tasks"></i></a> &nbsp;' .
                        '<a href="#" data-toggle="modal" data-target="#supplier-edit-modal" class="text-warning"  id="' . $rows->spl_id . '" title=" Edit"><i class="fas fa-edit"></i></a> &nbsp;' .
                        '<a href="javascript:void(0);" data-uid="' . $rows->spl_id . '" class="text-danger ifdel" title="Delete"><i class="fa fa-trash"></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(Request $request)
    {
        $validated = $request->validate(
            [
                'spl_contact' => 'required|numeric|unique:suppliers,spl_contact',
            ],
            [
                'spl_contact.required' => 'Contact Required',
                'spl_contact.numeric' => 'Contact must be a number',
                'spl_contact.unique' => 'Contact number is associated with another supplier.',
            ]
        );

        if ($request->ajax()) {
            $spl = new Suppliers();
            $spl->spl_name    = $request->spl_name;
            $spl->spl_contact = $request->spl_contact;
            $spl->spl_email   = $request->spl_email;
            $spl->spl_address = $request->spl_address;
            $spl->spl_notes   = $request->spl_notes;
            $spl->in_user = 'n/a';
            $spl->dated = date('Y-m-d H:i:s');
            if ($spl->save()) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    public function edit(Request $request)
    {
        $spl_id = $request->spl_id;

        $row = Suppliers::where('spl_id', $spl_id)->first();
        $spl_name    = null;
        $spl_contact = null;
        $spl_email   = null;
        $spl_address = null;
        $spl_notes   = null;
        if ($row) {
            $spl_name    = $row->spl_name;
            $spl_contact = $row->spl_contact;
            $spl_email   = $row->spl_email;
            $spl_address = $row->spl_address;
            $spl_notes   = $row->spl_notes;
        }

        echo json_encode([
            'spl_name' => $spl_name,
            'spl_contact' => $spl_contact,
            'spl_email' => $spl_email,
            'spl_address' => $spl_address,
            'spl_notes' => $spl_notes
        ]);
        // if (!$request->pur_req)) 
        //     echo json_encode(array($spl_name, $spl_contact, $spl_email, $spl_address, $spl_notes,));
        // }
    }

    public function update(Request $request)
    {
        $validated = $request->validate(
            [
                'spl_id' => 'required|numeric|exists:suppliers,spl_id',
                'spl_contact' => 'required|numeric|unique:suppliers,spl_contact,' . $request->spl_id . ' ,spl_id',
            ],
            [
                'spl_contact.required' => 'Contact Required',
                'spl_contact.numeric' => 'Contact must be a number',
                'spl_contact.unique' => 'Contact number is associated with another supplier.',
            ]
        );

        if ($request->ajax()) {
            $spl = Suppliers::where('spl_id', $request->spl_id)->first();
            if ($spl) {
                $spl->spl_name    = $request->spl_name;
                $spl->spl_contact = $request->spl_contact;
                $spl->spl_email   = $request->spl_email;
                $spl->spl_address = $request->spl_address;
                $spl->spl_notes   = $request->spl_notes;
                $spl->in_user = 'n/a';
                $spl->dated = date('Y-m-d H:i:s');
                if ($spl->save()) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
    }

    public function delete(Request $request)
    {
        $validated = $request->validate(
            [
                'spl_id' => 'required|numeric|exists:suppliers,spl_id',
            ],
            [
                'spl_id.required' => 'Supplier required',
                'spl_contact.exists' => 'Supplier does not exits, please refresh the page and try again',
            ]
        );
        if ($request->ajax()) {
            $del = Suppliers::where('spl_id', $request->spl_id)->delete();
            if ($del) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    public function getInvoices(Request $request)
    {
        $spl_id  = $request->spl_id;
        $query = Purchases::where('spl_id', $spl_id)->get();
        if ($query->count() > 0) {
            $sno = 0;
            $table = '<table class="table">
							<tr>
								<th> Sno </th>
								<th> Invoice # </th>
								<th> Amount </th>
								<th> Paid </th>
								<th> Balance </th>
								<th> Action </th>
							</tr>';
            foreach ($query as $rows) {

                $sno++;
                $total_paid = 0;

                $pq = PurchasePayments::where('invoice', $rows->invoice)->get();
                if ($pq->count() > 0) {

                    foreach ($pq as $pr) {
                        $total_paid += $pr->amount;
                    }
                }
                $advance = Purchases::where('invoice', $rows->invoice)->value('advance');
                $table .= '<tr>
					 			<td>' . $sno . '</td>
					 			<td>' . $rows->invoice . ' <a href="javascript:void(0);" target="_blank" class="m-r-10"><i class="fa fa-print text-info"></i></a></td>
					 			<td class="text-purple">' . $rows->sub_total . '</td>
					 			<td class="text-success">' . ($total_paid + $advance) . '</td>
					 			<td class="text-danger">' . ($rows->sub_total - ($total_paid + $advance)) . '</td>
					 			<td><a href="' . $rows->sub_total . '" title="' . $advance . '" data-toggle="modal" data-target="#make-payment-modal" id="' . $rows->invoice . '" class="text-primary"><i class="fa fa-plus"> Make Payment</i></a></td>
					 		   </tr>';
            }
            $table .= '</table>';
        } else {
            $table = 'No Invoices for this supplier';
        }
        echo json_encode(array($table));
    }

    public function getPayments(Request $request)
    {
        $tr = null;
        $invoice = $request->invoice;
        $amount  = $request->amount;
        $query = PurchasePayments::where('invoice', $invoice)->orderBy('pay_id', 'ASC')->get();
        if ($query->count() > 0) {
            $q = Purchases::where('invoice', $invoice)->first();
            if ($q) {
                $r = $q;
                $advance = $r->advance;
            }
            if ($request->sadv) {
                $amount = ($amount - $advance);
            }
            foreach ($query as $rows) {
                $amount = ($amount - $rows->amount);
                $tr .= '<tr>
								<td></td>
								<td class="paid_amount">' . $rows->amount . '</td>
								<td class="pamount">' . $amount . '</td>
								<td>' . $rows->dated . '</td>
								<td>' . $rows->type . '</td>
								<td>' . $rows->chq . '</td>
								<td>' . $rows->chqd . '</td>
								<td><a href="javascript:void(0);" class="text-danger rmv-supplier-payments" id="' . $rows->pay_id . '"><i class="fa fa-times"></i></a></td>
							</tr>';
            }
        }
        echo json_encode(array($tr));
    }
    public function makePayments(Request $request)
    {
        $invoice = $request->invoice;
        $pamount = $request->pamount;
        $bank    = $request->bank;
        $cheque  = $request->cheque;
        $chequed  = $request->chequed;
        if ($bank == "") {
            $bank = "Cash";
            $cheque = "Cash";
        }
        $ins_array = ['invoice' => $invoice, 'amount' => $pamount, 'type' => $bank, 'chq' => $cheque, 'chqd' => $chequed, 'dated' => now()];
        $ins_query = PurchasePayments::create($ins_array);
        if ($ins_query) {
            $msg = 1;
        } else {
            $msg = 0;
        }
        echo json_encode([$msg]);
    }

    public function removePayments(Request $request)
    {
        $pay_id = $request->pay_id;
        $deleted = PurchasePayments::where('pay_id', $pay_id)->delete();
        if ($deleted == 1) {
            echo 1;
        } else {
            echo 0;
        }
    }
}
