<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;
use Illuminate\Http\Request;
use App\Models\Education;
use App\Models\NextOfKin;
use App\Models\Guarantor;
use App\Models\User;
use App\Models\Imprest;

class UsersController extends Controller
{
    public function dashboard(Request $request)
    {
        $user = User::where('id', '=', Auth::id())->first();
        $education = Education::where('user_id', '=', Auth::id())->get();
        $nextOfKin = NextOfKin::where('user_id', '=', Auth::id())->first();
        $guarantor = Guarantor::where('user_id', '=', Auth::id())->get();

        $checkEducation = Education::where('user_id', '=', $user->id)->count();
        $checkNextOfKin = NextOfKin::where('user_id', '=', $user->id)->count();
        $checkGuarantor = Guarantor::where('user_id', '=', $user->id)->count();

        if (!$user->phone_verified_at) {
            return redirect()->intended('phone-Verification');
        }
        if (!$user->address) {
            return redirect()->intended('personal-info');
        }
        if ($checkEducation == 0) {
            return redirect()->intended('education');
        }
        if ($checkNextOfKin == 0) {
            return redirect()->intended('next-of-kin');
        }
        if ($checkGuarantor < 2) {
            return redirect()->intended('guarantor');
        }

        return view('dashboard.index', ["user" => $user, "educations" => $education, "nextOfKin" => $nextOfKin, "guarantor" => $guarantor]);
    }

    public function imprest(Request $request)
    {
        $countInvoice = Imprest::where('user_id', '=', Auth::id())->count();
        $approvedInvoice = Imprest::where('user_id', '=', Auth::id())->where('status', '=', "approved")->orwhere('status', '=', "paid")->count();
        $pendingInvoice = Imprest::where('user_id', '=', Auth::id())->where('status', '=', "pending")->count();
        $canceledInvoice = Imprest::where('user_id', '=', Auth::id())->where('status', '=', "canceled")->count();
        $loadedInvoice = Imprest::where('user_id', '=', Auth::id())->get();

        return view('dashboard.Imprest', ["invoices" => $loadedInvoice, "countInvoice" => $countInvoice, "approvedInvoice" => $approvedInvoice, "pendingInvoice" => $pendingInvoice, "canceledInvoice" => $canceledInvoice]);
    }

    public function viewImprest(Request $request)
    {
        $getImpress = null;
        $id = $request->get('id');
        if (!empty($id)) {
            $getImpress = Imprest::where('user_id', '=', Auth::id())->where('id', '=', $id)->first();
        }
        return view('dashboard.invoice', ["invoice" => $getImpress, "invoiceId" => $id]);
    }

    public function cancelImprest(Request $request){
        $credentials = $request->validate([
            'invoiceId' => ['required'],
        ]);

        $getInvoice = Imprest::where('id', '=',  $credentials["invoiceId"])->where('user_id','=', Auth::id())->first();
        if (!$getInvoice) {
            return back()->withErrors([
                'invoce' => 'The provided details do not match our records.',
            ])->withInput();
        }
        Imprest::where('id', '=',  $getInvoice->id)->update([
            "status" => "canceled",
            'updated_at' => Carbon::now()
        ]);
        
        $message = "Imprest canceled successfully.";
        return back()->with('message', $message);
    }

    public function invoice(Request $request)
    {
        $credentials = $request->validate([
            'bankName' => ['required'],
            'accountNumber' => ['required'],
            'accountName' => ['required'],
            'sumAmount' => ['required'],
            'items' => ['required'],
            'invoiceId' => []
        ]);

        $sumAmount = 0;
        $items = json_decode($credentials['items']);
        for ($i = 0; $i < count($items); $i++) {
            $sumAmount = $sumAmount + $items[$i]->amount;
        }
        $bankDetails = explode("|", $credentials['bankName']);
        // validate account number and bank details before miving forwared

        // fix department block
        $message = "";
        if (!empty($credentials["invoiceId"])) {
            Imprest::where('id', '=', $credentials["invoiceId"])->update([
                "amount" =>   $sumAmount * 100,
                "accountNumber" =>   $credentials["accountNumber"],
                "accountName" =>   $credentials["accountName"],
                "bankCode" =>  $bankDetails[0],
                "bank" =>  $bankDetails[1],
                "items" =>  $credentials["items"],
                'updated_at' => Carbon::now()
            ]);

            $message = "Imprest record updated successfully. Pending approval";
        } else {
            $imprest = new Imprest();
            $imprest->user_id = Auth::id();
            $imprest->amount = $sumAmount * 100;
            $imprest->accountNumber = $credentials["accountNumber"];
            $imprest->accountName = $credentials["accountName"];
            $imprest->bankCode = $bankDetails[0];
            $imprest->bank = $bankDetails[1];
            $imprest->items = $credentials["items"];
            $imprest->save();

            $message = "Imprest record added successfully. Pending approval";
        }


        return back()->with('message', $message);
    }

    public function updateImage(Request $request){
        $request->validate([
            'profileUpdate' => ['required', 'max:1000'],
        ]);
        $imageName = Storage::disk('public')->put('/images', $request->profileUpdate);
        $imageName = basename($imageName);

        User::where('id', '=', Auth::id())->update([
            'img' => "storage/images/" . $imageName
        ]);

        return back();
    }
}
