<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\MiscellaneousCharge;
use App\Models\XeroCustomer;
use DateTime;

class MiscellaneousChargesController extends Controller
{
    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index()
    {
        $charges = MiscellaneousCharge::orderBy('created_at', 'desc')->paginate(15);

        return view('charges.index', compact('charges'));
    }

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function create()
    {
        $customers = XeroCustomer::all();
        return view('charges.create', compact('customers'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'customer_id' => 'required|integer',
            'date_invoice' => 'string|required',
            'price' => 'required|between:0,1000000000099.99',
            'description' => 'string|required',

        ]);
        $validatedData = $request->all();

        $charge = new MiscellaneousCharge();
        $charge->customer_id = $validatedData['customer_id'];
        $charge->price = $validatedData['price'];
        $charge->description = $validatedData['description'];

        if ($validatedData['date_invoice'] == 'next_day') {
            $day = date('l');
            if ($day == 'Friday' || $day == 'Saturday' || $day == 'Sunday') {
                $nextMonday = strtotime('next monday');
                $date_invoice = date('Y-m-d', $nextMonday);
            } else {
                $datetime = new DateTime('tomorrow');
                $date_invoice = $datetime->format('Y-m-d');
            }
        } elseif ($validatedData['date_invoice'] == 'end_of_the_week') {
            $nextMonday = strtotime('next monday');
            $date_invoice = date('Y-m-d', $nextMonday);
        } elseif ($validatedData['date_invoice'] == 'end_of_the_month') {
            $firstDayNextMonth = strtotime('first day of next month');
            if (date('l', $firstDayNextMonth) == 'Saturday') {
                $firstDayNextMonth = strtotime('+2 days', $firstDayNextMonth);
            } elseif (date('l', $firstDayNextMonth) == 'Sunday') {
                $firstDayNextMonth = strtotime('+ 1 days', $firstDayNextMonth);
            }
            $date_invoice = date('Y-m-d', $firstDayNextMonth);

        }
        $charge->date_invoice = $date_invoice;
        $charge->date_invoiced = $validatedData['date_invoice'];
        $charge->save();
        return redirect()->route('charges.show', ['id' => $charge->id]);
    }

    /**
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function show($id)
    {
        $charge = MiscellaneousCharge::find($id);
        return view('charges.show', compact('charge'));
    }

    /**
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function edit($id)
    {
        $charge = MiscellaneousCharge::find($id);
        $customers = XeroCustomer::all();
        return view('charges.edit', compact('charge', 'customers'));
    }

    /**
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'customer_id' => 'required|integer',
            'date_invoice' => 'string|required',
            'price' => 'required|between:0,1000000000099.99',
            'description' => 'string|required',

        ]);
        $validatedData = $request->all();

        $charge = MiscellaneousCharge::find($id);
        $charge->customer_id = $validatedData['customer_id'];
        $charge->price = $validatedData['price'];
        $charge->description = $validatedData['description'];

        if ($validatedData['date_invoice'] == 'next_day') {
            $day = date('l');
            if ($day == 'Friday' || $day == 'Saturday' || $day == 'Sunday') {
                $nextMonday = strtotime('next monday');
                $date_invoice = date('Y-m-d', $nextMonday);
            } else {
                $datetime = new DateTime('tomorrow');
                $date_invoice = $datetime->format('Y-m-d');
            }
        } elseif ($validatedData['date_invoice'] == 'end_of_the_week') {
            $nextMonday = strtotime('next monday');
            $date_invoice = date('Y-m-d', $nextMonday);
        } elseif ($validatedData['date_invoice'] == 'end_of_the_month') {
            $firstDayNextMonth = strtotime('first day of next month');

            if (date('l', $firstDayNextMonth) == 'Saturday') {
                $firstDayNextMonth = strtotime('+2 days', $firstDayNextMonth);
            } elseif (date('l', $firstDayNextMonth) == 'Sunday') {

                $firstDayNextMonth = strtotime('+1 days', $firstDayNextMonth);
            }
            $date_invoice = date('Y-m-d', $firstDayNextMonth);

        }
        $charge->date_invoice = $date_invoice;
        $charge->date_invoiced = $validatedData['date_invoice'];
        $charge->save();
        return redirect()->route('charges.show', ['id' => $charge->id]);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        $charge = MiscellaneousCharge::find($id);
        $charge->delete();
        return redirect()->route('charges.index');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     * @throws \Illuminate\Validation\ValidationException
     */
    public function search(Request $request)
    {
        $this->validate($request, [
            'search' => 'string',
        ]);
        $validatedData = $request->all();

        $charges = MiscellaneousCharge::where('description', 'like', '%' . $validatedData['search'] . '%')
            ->orWhereHas('customer', function ($query) use ($validatedData) {
                return $query->where('xero_name', 'like', '%' . $validatedData['search'] . '%');
            })->orderBy('created_at', 'asc')->get();
        $search_query = $validatedData['search'];
        return view('charges.search', compact('charges', 'search_query'));
    }

}
