<?php

namespace App\Http\Controllers;

use App\Cawangan;
use App\Palsu;
use App\Pampasan;
use App\Panjar;
use App\Tebus;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Log\Logger;
use Illuminate\Support\Facades\Log;

class PampasanController extends Controller
{

    public function terimaPampasan(Request $request)
    {
        $validated =  $this->validate($request, [
            'norujukan'       => 'required|string',
            'kodcaw'          => 'required|string',
            'jumlah_pampasan' => 'required|numeric',
            'denominasi'      => 'required|array',
            'teller'          => 'required|string',
        ]);

        try {
            $cawangan = $this->getCawangan($request->kodcaw);

            if (!$cawangan) {
                return $this->errorResponse('Cawangan tidak dijumpai untuk kodcaw: ' . $request->kodcaw, 404);
            }

            $pampasan = Pampasan::on($cawangan['mysql'])
                ->where('norujukan', $validated['norujukan'])
                ->first();

            $pampasan->update([
                'jumlah_pampasan' => $validated['jumlah_pampasan'],
                'denominasi'      => isset($validated['denominasi']) ? json_encode($validated['denominasi']) : null,
                'teller'          => $validated['teller'],
            ]);

            return $this->successResponse('Pampasan berjaya dibayar.', $pampasan, 201);
        } catch (\Exception $e) {
            return $this->errorResponse('Database error: ' . $e->getMessage(), 500);
        }
    }

    public function updateStatusPampasan(Request $request)
    {
        $norujukan = $request->norujukan;

        $cawangan = $this->getCawangan($request->kodcaw);

        if (!$cawangan) {
            return $this->errorResponse('Cawangan tidak dijumpai untuk kodcaw: ' . $request->kodcaw, 404);
        }

        $tebus = Tebus::on($cawangan['mysql'])->where('norujukan', $norujukan)->first();

        $pampasan = Pampasan::on($cawangan['mysql'])->where("norujukan", $norujukan)->first();

        $pampasan->status = 1;

        $pampasan->save();

        // Update corresponding palsu table record status to 1
        Palsu::on($cawangan['mysql'])
            ->where('norujukan', $norujukan)
            ->update(['status' => 1]);

        return $this->successResponse('Status Pampasan berjaya dituntut.', $pampasan, 201);
    }

    public function getPampasan(Request $request)
    {
        $cawangan_connection = Cawangan::where('kodcaw', $request->kodcaw)->first()->mysql;

        $pampasan = Pampasan::on($cawangan_connection)
            ->when($request->filled('norujukan'), function ($query) use ($request) {
                return $query->where('norujukan',  $request->norujukan);
            })
            ->get();


        return $this->successResponse('Senarai pampasan', $pampasan, 201);
    }

    public function updateAgreementPrintedAt(Request $request)
    {
        $validated = $this->validate($request, [
            'norujukan' => 'required|string',
            'kodcaw'    => 'required|string',
        ]);

        try {
            $cawangan = $this->getCawangan($validated['kodcaw']);

            if (!$cawangan) {
                return $this->errorResponse('Cawangan tidak dijumpai untuk kodcaw: ' . $validated['kodcaw'], 404);
            }

            $pampasan = Pampasan::on($cawangan['mysql'])->where('norujukan', $validated['norujukan'])->first();

            if (!$pampasan) {
                return $this->errorResponse('Pampasan tidak dijumpai untuk norujukan: ' . $validated['norujukan'], 404);
            }

            $pampasan->agreement_printed_at = Carbon::now();
            $pampasan->save();

            return $this->successResponse('Agreement printed timestamp berjaya dikemaskini.', $pampasan, 200);
        } catch (\Exception $e) {
            return $this->errorResponse('Database error: ' . $e->getMessage(), 500);
        }
    }

    public function initiatePampasan(Request $request)
    {
        $validated = $this->validate($request, [
            'norujukan' => 'required|string',
            'kodcaw'    => 'required|string',
            'teller'    => 'required|string',
            'baucerno'  => 'required|string',
        ]);

        try {
            $cawangan = $this->getCawangan($validated['kodcaw']);

            if (!$cawangan) {
                return $this->errorResponse('Cawangan tidak dijumpai untuk kodcaw: ' . $validated['kodcaw'], 404);
            }

            // Find the palsu record
            $palsu = Palsu::on($cawangan['mysql'])->where('norujukan', $validated['norujukan'])->first();

            if (!$palsu) {
                return $this->errorResponse('Barang kes tidak dijumpai untuk norujukan: ' . $validated['norujukan'], 404);
            }

            // Check if pampasan already exists for this norujukan
            $existingPampasan = Pampasan::on($cawangan['mysql'])->where('norujukan', $validated['norujukan'])->first();

            if ($existingPampasan) {
                // If pampasan exists, just update the agreement_printed_at
                $existingPampasan->agreement_printed_at = Carbon::now();
                $existingPampasan->save();

                return $this->successResponse('Agreement printed timestamp berjaya dikemaskini untuk pampasan sedia ada.', $existingPampasan, 200);
            }

            // Create new pampasan record based on palsu data
            $pampasan = Pampasan::on($cawangan['mysql'])->create([
                'norujukan'           => $palsu->norujukan,
                'baucerno'            => $validated['baucerno'],
                'kodcaw'              => $palsu->kodcaw,
                'jumlah_pampasan'     => $palsu->nilaimarhun,
                'teller'              => $validated['teller'],
                'status'              => 0,
                'agreement_printed_at' => Carbon::now(),
            ]);

            return $this->successResponse('Pampasan berjaya daftar dari rekod barang kes.', $pampasan, 201);
        } catch (\Exception $e) {
            return $this->errorResponse('Database error: ' . $e->getMessage(), 500);
        }
    }

    private function getCawangan($kodcaw)
    {
        $cawangan = Cawangan::on('mysql7')->where('kodcaw', $kodcaw)->first();

        if (!$cawangan) {
            return null;
        }

        return $cawangan;
    }

    private function errorResponse($message, $statusCode = 404)
    {
        return response()->json([
            'success' => false,
            'message' => $message,
        ], $statusCode);
    }

    private function successResponse($message, $data = null, $statusCode = 200)
    {
        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => $data,
        ], $statusCode);
    }
}
