<?php

namespace App\Livewire\Pos\Opname;

use App\Models\Opname;
use App\Models\OpnameTemp;
use App\Models\Settings;
use App\Models\Warehouse;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithFileUploads;

class OpnameInput extends Component
{
    use WithFileUploads;

    public $type;
    public $period;
    public $file;
    public $isloading = false;

    public function mount()
    {
        $this->type = "Global";
        $this->period = Carbon::now()->format('Y-m-d');
    }

    public function render()
    {
        Opname::where('id_user', Auth::user()->id)->delete();
        return view('livewire.pos.opname.opname-input');
    }

    public function firstClick()
    {
        $this->isloading = true;
        $this->dispatch('import');
    }

    #[On('import')]
    public function import()
    {
        $data = $this->validate([
            'file' => 'required',
        ]);

        OpnameTemp::where('id_user', Auth::user()->id)->delete();

        $file = fopen($this->file->getRealPath(), 'r');
        $skipFirstRow = true;

        $chunkSize = 100;
        $chunks = [];

        while (($data = fgetcsv($file)) !== false) {
            if ($skipFirstRow) {
                $skipFirstRow = false;
                continue;
            }

            $chunks[] = [
                'date' => $this->period,
                'type' => $this->type,
                'id_user' => Auth::user()->id,
                'code' => $data[0],
                'barcode' => $data[1],
                'name' => $data[2],
                'price' => $data[3],
                'opname' => $data[4]
            ];

            if (count($chunks) == $chunkSize) {
                OpnameTemp::insert($chunks);
                $chunks = [];
            }
        }

        if (!empty($chunks)) {
            OpnameTemp::insert($chunks);
        }

        fclose($file);

        Opname::where('id_user', Auth::user()->id)->delete();
        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();

        if ($this->type == "Global") {
            $whs = Warehouse::where('code', $setting->wh_code)->first();
            $pricelist = $whs->id_pricelist;

            #insert opname
            DB::statement("
                INSERT INTO \"Luv2_opname\" (\"date\", \"type\", \"code\", \"barcode\", \"name\", \"price\", \"onhand\", \"id_user\") 
                SELECT '" . $this->period . "', '" . $this->type . "', \"code\", \"barcode\", \"name\", COALESCE((select \"price\" from \"Luv2_item_pricelist\" where \"item_code\"=a.\"code\" and \"id_pricelist\"='" . $pricelist . "'),0), COALESCE((select sum(\"qty\") from \"Luv2_item_trans\" where \"item_code\"=a.\"code\" and \"date\"<='" . $this->period . "'),0), '" . Auth::user()->id . "'
                FROM \"Luv2_item\" a
                ORDER BY \"code\", \"barcode\", \"name\"; 
                ");

            #update opname
            DB::statement("
                UPDATE \"Luv2_opname\"
                SET \"opname\" = \"b\".\"qty\"
                FROM (
                    SELECT \"code\", SUM(\"opname\") \"qty\"
                    FROM \"Luv2_opname_temp\"
                    WHERE \"date\"='" . $this->period . "' and \"id_user\"='" . Auth::user()->id . "'
                    GROUP BY \"code\"
                ) AS \"b\"
                WHERE \"Luv2_opname\".\"code\" = \"b\".\"code\"
                    AND \"Luv2_opname\".\"date\"='" . $this->period . "' and \"Luv2_opname\".\"id_user\" = '" . Auth::user()->id . "';
                ");
        } else {
            #insert opname
            DB::statement("
                INSERT INTO \"Luv2_opname\" (\"date\", \"type\", \"code\", \"barcode\", \"name\", \"price\", \"opname\", \"id_user\") 
                SELECT \"date\", \"type\", \"code\", \"barcode\", \"name\", avg(\"price\") \"price\", sum(\"opname\") \"opname\", \"id_user\"
                FROM \"Luv2_opname_temp\"
                WHERE \"date\"='" . $this->period . "' and \"id_user\"='" . Auth::user()->id . "'
                GROUP BY \"date\", \"type\", \"code\", \"barcode\", \"name\", \"id_user\"; 
                ");

            #update opname
            DB::statement("
                UPDATE \"Luv2_opname\"
                SET \"onhand\" = \"b\".\"qty\"
                FROM (
                    SELECT \"item_code\", SUM(\"qty\") \"qty\"
                    FROM \"Luv2_item_trans\"
                    WHERE \"date\" <= '" . $this->period . "'
                    GROUP BY \"item_code\"
                ) AS \"b\"
                WHERE \"Luv2_opname\".\"code\" = \"b\".\"item_code\"
                    AND \"Luv2_opname\".\"date\"='" . $this->period . "' and \"Luv2_opname\".\"id_user\" = '" . Auth::user()->id . "';
                ");
        }

        #update difference
        DB::statement("
        UPDATE \"Luv2_opname\" SET \"difference\" = \"opname\" - \"onhand\" WHERE \"date\"='" . $this->period . "' and \"id_user\" = '" . Auth::user()->id . "';
        ");

        OpnameTemp::where('id_user', Auth::user()->id)->delete();
        $this->isloading = false;
        return $this->redirect('/opname/result', navigate: true);
    }

    public function downloadTemplate()
    {
        $filePath = public_path('assets/templateso.csv');

        return Response::download($filePath);
    }
}
