<?php

namespace App\Imports;

use App\Models\ContactPoint;
use App\Models\PointTransaction;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Carbon\Carbon;

class PointImport implements ToCollection, WithHeadingRow
{
    protected $date;
    protected $staff;

    public function __construct($date, $staff)
    {
        $this->date = date("Y-m-d", strtotime($date));
        $this->staff = $staff;
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            $contact_id = $row['contact_id'];
            $name       = $row['name']; // opsional
            $newPoint   = $row['poin'];

            if (!$contact_id || $newPoint === null) continue;

            $point = ContactPoint::where('contact_id', $contact_id)->first();

            if ($point) {
                $oldPoint = $point->total_point;
                $selisih  = $newPoint - $oldPoint;

                $point->total_point  = $newPoint;
                $point->last_updated = $this->date;
            } else {
                $point = new ContactPoint();
                $point->contact_id   = $contact_id;
                $point->total_point  = $newPoint;
                $point->last_updated = $this->date;

                $selisih = $newPoint;
            }

            $point->save();

            $transaction = new PointTransaction();
            $transaction->customer_id = $contact_id;
            $transaction->type        = 'adjust';
            $transaction->point       = $selisih;
            $transaction->date        = $this->date;
            $transaction->staff       = $this->staff;
            $transaction->save();
        }
    }
}
