<?php

namespace App\Http\Controllers\Processing;

use App\Http\Controllers\Controller;
use App\Models\CustomerAccount;
use App\Models\DocumentHeader;
use App\Models\DocumentLink;
use Illuminate\Support\Facades\DB;

class CustomerProcessingController extends Controller
{
    public function index()
    {
        $customers = DB::table('customer_accounts as ca')
            ->leftJoin('customer_categories as cc', 'cc.id', '=', 'ca.category_id')
            ->select([
                'ca.id',
                'ca.customer_code',
                'ca.customer_account',
                DB::raw('COALESCE(cc.name, "Uncategorised") as category_name'),
                DB::raw('(
                    COALESCE((SELECT SUM(dh.inclusive_total) FROM document_headers dh WHERE dh.customer_account_id = ca.id AND dh.type = "invoice" AND dh.status <> "paid"), 0)
                    -
                    COALESCE((SELECT SUM(rl.amount) FROM receipts r JOIN receipt_lines rl ON rl.receipt_id = r.id WHERE r.customer_id = ca.id), 0)
                ) as outstanding_balance'),
            ])
            ->orderBy('ca.customer_account')
            ->paginate(25);

        return view('processing.customers.index', compact('customers'));
    }

    public function show(CustomerAccount $customer)
    {
        $documents = DocumentHeader::query()
            ->where('customer_account_id', $customer->id)
            ->orderByDesc('document_date')
            ->orderByDesc('id')
            ->paginate(25);

        $links = DocumentLink::query()
            ->where(function ($q) use ($customer) {
                $q->whereIn('source_id', DocumentHeader::query()->where('customer_account_id', $customer->id)->select('id'))
                  ->orWhereIn('target_id', DocumentHeader::query()->where('customer_account_id', $customer->id)->select('id'));
            })
            ->orderByDesc('id')
            ->get();

        return view('processing.customers.show', compact('customer', 'documents', 'links'));
    }
}
