<?php

namespace Modules\Client\Http\Controllers\Api;

use Illuminate\Support\Facades\DB;
use App\Helpers\Helper;
use App\Models\Claim;
use App\Models\CorporateEmployee;
use App\Models\Icd;
use App\Models\ClaimHistoryCare;
use App\Models\Corporate;
use App\Services\ClaimService;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Client\Transformers\ClaimShowResource;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Writer\Common\Creator\Style\StyleBuilder;
use Box\Spout\Common\Entity\Style\CellAlignment;
use Box\Spout\Common\Entity\Style\Color;

class ClaimController extends Controller
{
    public function __construct(public ClaimService $claimService)
    {
    }

    public function status($corporate_id)
    {
        $claims = $this->claimService->getCountClaimRequestPerStatus($corporate_id);

        // dd($claims);

        return Helper::responseJson([
            'count_requested' => 0,
            'count_approval' => 0,
            'count_disbrushment' => 0,
            'count_rejected' => 0,
        ]);
    }

    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request, $corporate_id)
    {
        $claims = Claim::query()
            ->when($request->search ?? null, function ($query, $search) {
                $query->where('code', 'LIKE', '%' . $search . '%');
            })
            ->with([
                'member',
                'diagnoses' => function ($diagnosis) {
                    return $diagnosis->where('type', 'primary');
                },
                'diagnoses.icd',
                'plan',
                'benefit',
                'claimRequest',
                'claimRequest.service'
            ])
            ->paginate(10);

        return Helper::responseJson($claims);
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('client::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        $claim = Claim::query()
            ->with([
                'member',
                'member.currentPlan',
                'member.currentPlan.benefits',
                'member.currentCorporate',
                'member.currentPolicy',
                'diagnosis',
                'diagnoses',
                'benefit',
                'files',
                'claimRequest',
                'claimRequest.files',
                'items',
                'items.claim_itemable',
            ])
            ->findOrFail($id);

        return Helper::responseJson(ClaimShowResource::make($claim));
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('client::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }

    public function export($corporate_id){
        $corporate = Corporate::where('id', $corporate_id)->with(['currentPolicy'])->first();
        $member_id = CorporateEmployee::where('corporate_id', $corporate_id)->get('member_id')->toArray();
        // dd($member_id);
        $claim = Claim::whereIn('member_id', $member_id)->with(['member', 'member.plans'])->get();
        $data = [];

        if (count( $claim) > 0){
            $temp = [];
            foreach($claim as $c) {

                $diagnosis = ClaimHistoryCare::where('claim_id', 34)->with('icd')->get();
                $diagnosisName = '';
                if (count($diagnosis) > 0){
                    $tempDiagnosis = [];
                    foreach($diagnosis as $key => $d){
                       $diagnosis = Icd::where('id', $d['main_diagnosis_id'])->first();
                        array_push($tempDiagnosis, $diagnosis->name);
                    }

                    $diagnosisName = implode(", ", $tempDiagnosis);

                }
                $temp['id'] = $c['id'];
                $temp['plan_id'] = $c['member']['plans'][0]['code'];
                $temp['payor_id'] = $c['member']['payor_id'];
                $temp['corporate_id'] = $corporate->name;
                $temp['policy_number'] = $corporate->currentPolicy->code;
                $temp['member_id'] = $c['member']['member_id'];
                $temp['benefit_code'] = $c['benefit_code'];
                $temp['benefit_desc'] = $c['benefit_desc'];
                $temp['amount_incurred'] = $c['amount_incurred'];
                $temp['amount_approved'] = $c['amount_approved'];
                $temp['amount_not_approved'] = $c['amount_not_approved'];
                $temp['excess_paid'] = $c['excess_paid'];
                $temp['diganosis'] = $diagnosisName;
                array_push($data, $temp);
            }

            $headers = [
                ['value' => 'Plan ID', 'cell' => 'A1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Payor ID', 'cell' => 'B1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Corporate ID', 'cell' => 'C1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Policy Number', 'cell' => 'D1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Member ID', 'cell' => 'E1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Benefit Code', 'cell' => 'F1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Benefit Desc', 'cell' => 'G1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Amt Incurred', 'cell' => 'H1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Amt Approved', 'cell' => 'I1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Amt Not Approved', 'cell' => 'J1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Excess Paid', 'cell' => 'K1', 'mergeCell' => false, 'mergeToCell' => ''],
                ['value' => 'Diagnosis', 'cell' => 'L1', 'mergeCell' => false, 'mergeToCell' => 'J2'],
                
            ];
    
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();

            foreach ($headers as $header) {
                $sheet->setCellValue($header['cell'], $header['value']);
    
                if ($header['mergeCell'] === true) {
                    $sheet->mergeCells($header['cell'] . ':' . $header['mergeToCell']);
                }
    
                $sheet->getStyle($header['cell'])->getFont()->setBold(true);
                $sheet->getStyle($header['cell'])->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
            }

            $startFrom = 2;

            foreach($data as $i => $d){
                $sheet->setCellValue('A' . $startFrom, $d['plan_id'] ?? '-');
                $sheet->setCellValue('B' . $startFrom, $d['payor_id'] ?? '-');
                $sheet->setCellValue('C' . $startFrom, $d['corporate_id'] ?? '-');
                $sheet->setCellValue('D' . $startFrom, $d['policy_number'] ?? '-');
                $sheet->setCellValue('E' . $startFrom, $d['member_id'] ?? '-');
                $sheet->setCellValue('F' . $startFrom, $d['benefit_code'] ?? '-');
                $sheet->setCellValue('G' . $startFrom, $d['benefit_desc'] ?? '-');
                $sheet->setCellValue('H' . $startFrom, $d['amount_incurred'] ?? '-');
                $sheet->setCellValue('I' . $startFrom, $d['amount_approved'] ?? '-');
                $sheet->setCellValue('J' . $startFrom, $d['amount_not_approved'] ?? '-');
                $sheet->setCellValue('K' . $startFrom, $d['excess_paid'] ?? '-');
                $sheet->setCellValue('L' . $startFrom, $d['diganosis'] ?? '-');
                
                $startFrom++;
            }

            foreach (['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K'] as $header) {
                if ($header === 'A') {
                    $spreadsheet->getActiveSheet()->getColumnDimension($header)->setWidth(35, 'px');
                } elseif ($header === 'H' || $header === 'I') {
                    $spreadsheet->getActiveSheet()->getColumnDimension($header)->setWidth(100, 'px');
                } else {
                    $spreadsheet->getActiveSheet()->getColumnDimension($header)->setAutoSize(true);
                }
            }

            $spreadsheet->getActiveSheet()->getStyle('A2:A' . $startFrom)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);

            $sheet->getDefaultRowDimension()->setRowHeight(-1);
            $sheet->setTitle('Alarm Center Report');
    
            $writer = new Xlsx($spreadsheet);
            ob_start();
            $writer->save('php://output');
            $content = ob_get_contents();
            ob_end_clean();
    
            $fileName = 'result-' . now()->getPreciseTimestamp(3) . '-alarm-center-report.xlsx';
            Storage::disk('public')->put('temp/' . $fileName, $content);
    
            $fileUrl = url('storage/temp/' . $fileName);
    
            return Helper::responseJson([
                "file_url" => $fileUrl
            ]);
        }
    }

    public function exportAlrmCenter($corporate_id, $start, $end)
    {
        $writer = WriterEntityFactory::createXLSXWriter();
        $writer->openToFile(public_path('files/Report-Data-Alarm-Center-'.$start.'-'.$end.'.xlsx'));
        
        $header = [
            'No',
            'Code',
            'Date Submission',
            'Date Discharge',
            'Provider',
            'Member ID (BN)',
            'Member Name',
            'Member Name Principal',
            'Plan Code',
            'Payor ID',
            'Corporate name',
            'Policy Number',
            'Total Billing',
            'Benefit Code',
            'Benefit Desc',
            'Amt Incurred',
            'Amt Approved',
            'Amt Not Approved',
            'Excess Paid',
            'Diagnosis',
            'Keterangan',
            'Catatan'
        ];
        $style = (new StyleBuilder())
           ->setFontBold()
        //    ->setFontSize(15)
        //    ->setFontColor(Color::BLUE)
        //    ->setShouldWrapText()
           ->setCellAlignment(CellAlignment::LEFT)
        //    ->setBackgroundColor(Color::YELLOW)
           ->build();

        $headerRow = WriterEntityFactory::createRowFromArray($header, $style);
        $writer->addRow($headerRow);
        
        $data = DB::table('request_logs')
        ->leftJoin('members', 'members.id', '=', 'request_logs.member_id')
        ->leftJoin('corporate_employees','corporate_employees.member_id','=','members.id')
        ->where('corporate_employees.corporate_id', '=', $corporate_id)
        ->where('request_logs.status_final_log', '=', 'approved')
        ->where('request_logs.deleted_at', '=', null)
        ->when($start != 'all' && $end != 'all', function ($query) use ($start, $end) {
            $query->where('request_logs.submission_date', '>=', $start)
                ->where('request_logs.submission_date', '<=', $end);
        })       
        ->select(
            DB::raw('1 AS no'),
            'request_logs.submission_date',
            'request_logs.discharge_date',
            'request_logs.organization_id',
            'request_logs.id',
            'request_logs.member_id',
            'request_logs.service_code',
            'request_logs.code',
            'request_logs.diagnosis',
            'request_logs.keterangan',
            'request_logs.catatan'
        )
        ->groupBy(
            'request_logs.submission_date',
            'request_logs.discharge_date',
            'request_logs.organization_id',
            'request_logs.id',
            'request_logs.member_id',
            'request_logs.service_code',
            'request_logs.code',
            'request_logs.diagnosis',
            'request_logs.keterangan',
            'request_logs.catatan'
        )
        ->orderBy('request_logs.submission_date')
        ->get();

        if (isset($data) && count($data) > 0) 
        {
            $dataRow = array();
            $no = 0;
            foreach ($data as $item)
            {
                //Provider
                $dataRumahSakit = DB::table('organizations')
                ->leftJoin('addresses', 'addresses.addressable_id', '=', 'organizations.id')
                ->where('organizations.id', '=', $item->organization_id)
                ->where('addresses.addressable_type', '=', 'App\Models\Organization')
                ->select('organizations.name AS nama_rumahsakit', 'addresses.text AS alamat_rumahsakit')
                ->first();
                //Data Member
                $dataMember = DB::table('members')
                ->where('members.id', '=', $item->member_id)
                ->select(
                    'members.nric',
                    'members.id',
                    'members.principal_id',
                    'members.name',
                    'members.birth_date',
                    'members.member_id',
                    'members.gender',
                    DB::raw('
                        (Select persons.nik FROM persons WHERE persons.id = members.person_id LIMIT 1) AS nik
                    '),
                    DB::raw('
                        "LinkSehat" AS penjamin
                    '),
                    DB::raw('
                        (Select corporates.name FROM corporates
                            LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                            WHERE corporate_employees.member_id = members.id LIMIT 1) AS nama_perusahaan
                    '),
                    DB::raw('
                        (Select corporates.id FROM corporates
                            LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                            WHERE corporate_employees.member_id = members.id LIMIT 1) AS id_perusahaan
                    '),
                    DB::raw('
                        (Select corporates.code FROM corporates
                            LEFT JOIN corporate_employees ON corporate_employees.corporate_id = corporates.id
                            WHERE corporate_employees.member_id = members.id LIMIT 1) AS code_perusahaan
                    '),
                    DB::raw('
                        (Select services.name FROM services
                            WHERE services.code = "'.$item->service_code.'" LIMIT 1) AS jenis_perwatan
                    '),
                    DB::raw('
                        (Select member_policies.policy_id FROM member_policies WHERE member_policies.member_id = members.member_id LIMIT 1) AS no_polis
                    '),
                    DB::raw('
                    (Select member_policies.status FROM member_policies WHERE member_policies.member_id = members.member_id LIMIT 1) AS status_polis
                    '),
                    DB::raw('
                        (Select plans.code FROM member_plans
                            LEFT JOIN plans ON plans.id = member_plans.plan_id
                            WHERE member_plans.member_id = members.id AND plans.service_code = "'.$item->service_code.'" LIMIT 1) AS code_plan
                    '),
                    DB::raw('
                        (Select plans.limit_rules FROM member_plans
                            LEFT JOIN plans ON plans.id = member_plans.plan_id
                            WHERE member_plans.member_id = members.id LIMIT 1) AS limit_rules
                    '),
                    DB::raw('
                        "IDR" AS mata_uang
                    '),
                    'members.members_effective_date AS mulai',
                    'members.members_expire_date AS akhir'
                    )
                ->first();

                //Nama Karyawan
                $data['namaKaryawan'] = '';
                if($dataMember->principal_id)
                {
                    $dataNamaKaryawan =  DB::table('members')
                    ->where('members.member_id', '=', $dataMember->principal_id)
                    ->select('members.name')
                    ->first();
                    $data['namaKaryawan'] = $dataNamaKaryawan->name;
                }
                else{
                    $data['namaKaryawan'] = $dataMember->name;
                }

                //Data Benefit
                $dataClaimLog =  DB::table('request_log_benefits')
                ->where('request_log_benefits.request_log_id', '=', $item->id)
                ->select(
                    '*',
                    DB::raw('
                        (Select benefits.description FROM benefits
                            WHERE benefits.id = request_log_benefits.benefit_id LIMIT 1) AS benfit
                    '),
                    DB::raw('
                        (Select benefits.code FROM benefits
                            WHERE benefits.id = request_log_benefits.benefit_id LIMIT 1) AS code
                    ')
                )
                ->get();

                $check_first_id = 0;
                if($check_first_id != $item->id)
                {
                    $no += $item->no;
                }
                $total_billing = 0;
                $lastIndex = count($dataClaimLog) - 1;
                if (isset($dataClaimLog) && count($dataClaimLog) > 0) 
                {
                    foreach ($dataClaimLog as $index => $item_benefit)
                    {
                        $total_billing += !empty($item_benefit->amount_approved) ? $item_benefit->amount_approved : 0;
                        $rowData  = [
                            $check_first_id != $item->id ? $no : $no,
                            !empty($item->code) ? $item->code : '',
                            !empty($item->submission_date) ? $item->submission_date : '',
                            !empty($item->discharge_date) ? $item->discharge_date : '',
                            !empty($dataRumahSakit->nama_rumahsakit) ? $dataRumahSakit->nama_rumahsakit : '',
                            !empty($dataMember->member_id) ? $dataMember->member_id : '',
                            !empty($dataMember->name) ? $dataMember->name : '',
                            $data['namaKaryawan'],
                            !empty($dataMember->code_plan) ? $dataMember->code_plan : '',
                            'LinkSehat',
                            !empty($dataMember->nama_perusahaan) ? $dataMember->nama_perusahaan : '',
                            !empty($dataMember->no_polis) ? $dataMember->no_polis : '',
                            ($lastIndex == $index ? $total_billing : ''),
                            !empty($item_benefit->code) ? $item_benefit->code : '',
                            !empty($item_benefit->benfit) ? $item_benefit->benfit : '',
                            !empty($item_benefit->amount_incurred) ? $item_benefit->amount_incurred : '',
                            !empty($item_benefit->amount_approved) ? $item_benefit->amount_approved : '',
                            !empty($item_benefit->amount_not_approved) ? $item_benefit->amount_not_approved : '',
                            !empty($item_benefit->excess_paid) ? $item_benefit->excess_paid : '',
                            !empty($item->diagnosis) ? $item->diagnosis : '',
                            !empty($item->catatan) ? $item->catatan : '',
                            !empty($item->keterangan) ? $item->keterangan : '',
        
                        ];
                        array_push($dataRow,$rowData);
                        
                        $check_first_id = $item->id;
                    } 
                }
                else
                {
                    $rowData  = [
                        $check_first_id != $item->id ? $no : '',
                        !empty($item->code) ? $item->code : '',
                        !empty($item->submission_date) ? $item->submission_date : '',
                        !empty($item->discharge_date) ? $item->discharge_date : '',
                        !empty($dataRumahSakit->nama_rumahsakit) ? $dataRumahSakit->nama_rumahsakit : '',
                        !empty($dataMember->member_id) ? $dataMember->member_id : '',
                        !empty($dataMember->name) ? $dataMember->name : '',
                        $data['namaKaryawan'],
                        !empty($dataMember->code_plan) ? $dataMember->code_plan : '',
                        'LinkSehat',
                        !empty($dataMember->nama_perusahaan) ? $dataMember->nama_perusahaan : '',
                        !empty($dataMember->no_polis) ? $dataMember->no_polis : '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
    
                    ];
                    array_push($dataRow,$rowData);  

                }     
            }
            $style = (new StyleBuilder())
            //->setFontBold()
            //    ->setFontSize(15)
            //    ->setFontColor(Color::BLUE)
            //    ->setShouldWrapText()
            ->setCellAlignment(CellAlignment::LEFT)
            //    ->setBackgroundColor(Color::YELLOW)
            ->build();
            $grand_total_billing = 0;
            foreach ($dataRow as $rowData) {
                if (is_numeric($rowData[12])) {
                    // Jumlahkan nilai angka ke total
                    $grand_total_billing += $rowData[12];
                }
                $row = WriterEntityFactory::createRowFromArray($rowData, $style);
                $writer->addRow($row);
            }
            //Footer
            $footer = [
                'Total',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                $grand_total_billing,
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                ''
            ];
            $style = (new StyleBuilder())
               ->setFontBold()
            //    ->setFontSize(15)
            //    ->setFontColor(Color::BLUE)
            //    ->setShouldWrapText()
               ->setCellAlignment(CellAlignment::LEFT)
            //    ->setBackgroundColor(Color::YELLOW)
               ->build();
    
            $footerRow = WriterEntityFactory::createRowFromArray($footer, $style);
            $writer->addRow($footerRow);
        }
        $writer->close();

        return Helper::responseJson([
            'file_name' => 'Report-Data-Alarm-Center-'. $start.'-'.$end,
            "file_url" => url('files/Report-Data-Alarm-Center-'. $start.'-'.$end.'.xlsx')
        ]);
    }
}
