<?php

namespace App\Modules\Accounts;

use Illuminate\Support\Facades\View;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;
use App\Modules\Bookings\Task;
use App\Modules\Bookings\Repair;
use App\Modules\Bookings\Support;
use App\Modules\Bookings\Onsite;
use App\Http\Controllers\BaseController;

class AccountsController extends BaseController
{
    /**
     * The layout that should be used for responses.
     *
     * @var string
     */
    protected $layout = 'layouts.master';

    /**
     * Render the index page.
     *
     * @return void
     */
    public function getIndex()
    {
        $overview = [
            'owed' => Task::leftJoin('parts', function ($join) {
                            return $join->on('parts.related_id', '=', 'tasks.id')->where('parts.related_type', '=', 'task');
                        })
                        ->where('completed', 1)->where('paid', 0)
                        ->whereIn('tasks.type', ['repair', 'support', 'onsite'])
                        ->select(\DB::raw('SUM(labour) as labour, SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as parts'))->first()->toArray(),

            'overdue' => Task::leftJoin('parts', function ($join) {
                            return $join->on('parts.related_id', '=', 'tasks.id')->where('parts.related_type', '=', 'task');
                        })
                        ->where('completed', 1)->where('paid', 0)->overdue()
                        ->whereIn('tasks.type', ['repair', 'support', 'onsite'])
                        ->select(\DB::raw('SUM(labour) as labour, SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as parts'))->first()->toArray(),

            'piechart' => [
                'repairs' => intval(Repair::where('completed', 1)->repairs()->where('paid', 0)->sum('labour')),
                'support' => intval(Support::where('completed', 1)->support()->where('paid', 0)->sum('labour')),
                'onsite'  => intval(Onsite::where('completed', 1)->onsite()->where('paid', 0)->sum('labour')),
            ],
            'linechart' => Task::leftJoin('parts', function ($join) {
                            return $join->on('parts.related_id', '=', 'tasks.id')->where('parts.related_type', '=', 'task');
                        })
                        ->whereIn('tasks.type', ['repair', 'support', 'onsite'])
                        ->where('completed', 1)
                        ->where('paid', 0)
                        ->groupByRaw("DATE_FORMAT(tasks.completed_at, ?)", ['%Y-%m'])
                        ->selectRaw('DATE_FORMAT(tasks.completed_at, ?) as timestamp, SUM(labour) as labour, SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as parts', ['%d-%m-%Y'])
                        ->get()
                        ->toArray(),
        ];

        $this->layout->content = View::make('accounts::index', compact('overview'));
    }

    /**
     * Renders the page that display accounts stats for a particular client.
     *
     * @return void
     */
    public function getShow($client_id, $client_type)
    {
        if ($client_type == 'customer') {
            $client = Customer::find($client_id);
        } else {
            $client = Client::find($client_id);
        }

        $overview = [
            'owed' => Task::leftJoin('parts', function ($join) {
                            return $join->on('parts.related_id', '=', 'tasks.id')->where('parts.related_type', '=', 'task');
                        })
                        ->where('completed', 1)->where('paid', 0)->where('client_id', $client_id)->where('client_type', $client_type)
                        ->select(\DB::raw('SUM(labour) as labour, SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as parts'))->first()->toArray(),

            'overdue' => Task::leftJoin('parts', function ($join) {
                            return $join->on('parts.related_id', '=', 'tasks.id')->where('parts.related_type', '=', 'task');
                        })
                        ->where('completed', 1)->where('paid', 0)->where('client_id', $client_id)->where('client_type', $client_type)->overdue()
                        ->select(\DB::raw('SUM(labour) as labour, SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as parts'))->first()->toArray(),
        ];

        $this->layout->content = View::make('accounts::show', compact('client', 'client_type', 'overview'));
    }

    /**
     * Redirects to the main invoices page with client filter.
     *
     * @param int $client_id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getInvoices($client_id)
    {
        // Try to find the client in both clients and customers tables
        $client = Client::find($client_id);
        $client_type = 'client';
        
        if (!$client) {
            $client = Customer::find($client_id);
            $client_type = 'customer';
        }
        
        if (!$client) {
            abort(404, 'Client not found');
        }

        // Redirect to the main invoices page with client filter parameters
        return redirect()->to("/invoices#/invoices/browse?client_id={$client_id}&client_type={$client_type}");
    }
}
