<?php

namespace App\Http\Controllers;

use App\Audit;
use App\MaxMutuEmas;
use App\MaxPinjaman;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class MaxPinjamanController extends Controller
{
    public function getAllMaxPinjaman(Request $request)
    {
        if (config('parameter.max_mutuemas')) {
            $data = MaxMutuEmas::on('mysql7')->select('karat', 'teller', 'pc', 'operasi')->get();

            $calculateMargin = $this->calculateMaxPinjamanMutu($data, $request->mutu,$request->total_nilai_marhun);
            
            $pinjaman = [
                [
                    "user_type" => "teller",
                    "max" => $calculateMargin['teller'],
                    "teller_pinjaman" => $calculateMargin['teller_pinjaman']
                   
                ],
                [
                    "user_type" => "khazanah",
                    "max" => $calculateMargin['pc'],
                    "pc_pinjaman" => $calculateMargin['pc_pinjaman']
                ],
                [
                    "user_type" => "operasi",
                    "max" => $calculateMargin['operasi'],
                    "operasi_pinjaman" => $calculateMargin['operasi_pinjaman']
                ]
            ];
        } else {
            $pinjaman = MaxPinjaman::on('mysql7')->get();
        }
        return response()->json($pinjaman);
    }

    public function calculateMaxPinjamanMutu($data, $mutu,$totalMarhun)
    {
        $totalMaxMarhunPC = 0;
        $totalMaxMarhunTeller = 0;
        $totalMaxMarhunOperasi = 0;

        if($mutu == null || $totalMarhun == 0){
            return [
                "pc" => 0,
                "pc_pinjaman" => 0,
                "teller" => 0,
                "teller_pinjaman" => 0,
                "operasi" => 0,
                "operasi_pinjaman" => 0
            ];
        }
        $mutuKarat = array_map(function($item) {
            return $item[0];
        }, $mutu);
        $mutuNilai = array_map(function($item) {
            return $item[1];
        }, $mutu);  

        foreach($mutuKarat as $index => $karat){
            $margin = $data->where('karat', $karat)->first();
            if($margin){
                $nilai = $mutuNilai[$index];
                $totalMaxMarhunPC += round(($margin->pc/100) * $nilai, 2);
                $totalMaxMarhunTeller += round(($margin->teller/100) * $nilai, 2);
                $totalMaxMarhunOperasi += round(($margin->operasi/100) * $nilai, 2);
            }
        }

        $totalMaxPC = $totalMarhun > 0 ? ($totalMaxMarhunPC / $totalMarhun) * 100 : 0;
        $totalMaxTeller = $totalMarhun > 0 ? ($totalMaxMarhunTeller / $totalMarhun) * 100 : 0;
        $totalMaxOperasi = $totalMarhun > 0 ? ($totalMaxMarhunOperasi / $totalMarhun) * 100 : 0;
        return [
            "pc" => round($totalMaxPC,2),
            "pc_pinjaman" => round(($totalMaxPC / 100) * $totalMarhun, 2),
            "teller" => round($totalMaxTeller,2),
            "teller_pinjaman" => round(($totalMaxTeller / 100) * $totalMarhun, 2),
            "operasi" => round($totalMaxOperasi,2),
            "operasi_pinjaman" => round(($totalMaxOperasi / 100) * $totalMarhun, 2)
        ];
    }


    public function getAllMaxMutuEmas(Request $request)
    {
        $maxmutuemas = MaxMutuEmas::on('mysql7')->get();
        return response()->json($maxmutuemas);
    }

    public function getSpecificMaxMutuEmas(Request $request)
    {
        $karat = $request->karat;
        $nilaimarhun = $request->nilaimarhun;
        
        $nilaimarhun = preg_replace('/[^0-9.]/', '', $nilaimarhun); // Remove non-numeric characters except decimal point
        $nilaimarhun = is_numeric($nilaimarhun) ? (float)$nilaimarhun : 0;
        
        $maxmutuemas = MaxMutuEmas::on('mysql7')->where('karat', $karat)->first();

        if($maxmutuemas && $nilaimarhun > 0){
            $maxmutuemas->maxteller = round(($maxmutuemas->teller/100) * $nilaimarhun, 2);
            $maxmutuemas->maxpc = round(($maxmutuemas->pc/100) * $nilaimarhun, 2);
            $maxmutuemas->maxoperasi = round(($maxmutuemas->operasi/100) * $nilaimarhun, 2);
        } else if($maxmutuemas) {
            $maxmutuemas->maxteller = 0;
            $maxmutuemas->maxpc = 0;
            $maxmutuemas->maxoperasi = 0;
        }

        return response()->json($maxmutuemas);
    }

    public function updateMaxMutuEmas(Request $request)
    {
        // Validate the request manually for Lumen
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'recno' => 'required|integer',
            'karat' => 'required|string|max:10',
            'keterangan' => 'required|string|max:255',
            'teller' => 'required|numeric|min:0|max:100',
            'pc' => 'required|numeric|min:0|max:100',
            'operasi' => 'required|numeric|min:0|max:100',
            'username' => 'required|string|max:255'
        ], [
            'recno.required' => 'Nombor rekod diperlukan.',
            'recno.integer' => 'Nombor rekod mesti berupa nombor.',
            'karat.required' => 'Karat diperlukan.',
            'karat.string' => 'Karat mesti berupa teks.',
            'karat.max' => 'Karat tidak boleh lebih dari 10 aksara.',
            'keterangan.required' => 'Keterangan diperlukan.',
            'keterangan.string' => 'Keterangan mesti berupa teks.',
            'keterangan.max' => 'Keterangan tidak boleh lebih dari 255 aksara.',
            'teller.required' => 'Peratus teller diperlukan.',
            'teller.numeric' => 'Peratus teller mesti berupa nombor.',
            'teller.min' => 'Peratus teller mestilah sekurang-kurangnya 0.',
            'teller.max' => 'Peratus teller tidak boleh melebihi 100.',
            'pc.required' => 'Peratus PC diperlukan.',
            'pc.numeric' => 'Peratus PC mesti berupa nombor.',
            'pc.min' => 'Peratus PC mestilah sekurang-kurangnya 0.',
            'pc.max' => 'Peratus PC tidak boleh melebihi 100.',
            'operasi.required' => 'Peratus operasi diperlukan.',
            'operasi.numeric' => 'Peratus operasi mesti berupa nombor.',
            'operasi.min' => 'Peratus operasi mestilah sekurang-kurangnya 0.',
            'operasi.max' => 'Peratus operasi tidak boleh melebihi 100.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Pengesahan gagal',
                'errors' => $validator->errors()
            ], 422);
        }

        $recno = $request->recno;
        $karat = $request->karat;
        $keterangan = $request->keterangan;
        $teller = $request->teller;
        $pc = $request->pc;
        $operasi = $request->operasi;
        $username = $request->username;

        $current = \Carbon\Carbon::now();

        $maxmutuemas = MaxMutuEmas::on('mysql7')->where('recno', $recno)->first();
        
        if ($maxmutuemas) {
            $oldmax = $maxmutuemas->toJson();

            $maxmutuemas->karat = $karat;
            $maxmutuemas->keterangan = $keterangan;
            $maxmutuemas->teller = $teller;
            $maxmutuemas->pc = $pc;
            $maxmutuemas->operasi = $operasi;
            $maxmutuemas->tarikhupdate = \Carbon\Carbon::now();
            $maxmutuemas->save();

            Audit::create([
                'users' => $username,
                'actions' => 'Penukaran Mutu Margin',
                'norujukan' => '-',
                'new_data' => $maxmutuemas->toJson(),
                'old_data' => $oldmax,
                'kodcaw' => 'OPERASI',
                'created_at' => $current,
                'updated_at' => $current,
            ]);

            return response()->json([
                'status' => 'success',
                'message' => 'Max Mutu Emas updated successfully',
                'data' => $maxmutuemas
            ]);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Record not found'
            ], 404);
        }
    }
}