<?php

namespace App\Imports;

use App\Models\Product;
use App\Models\Stocktransaction;
use App\Models\Substocktransaction;
use App\Models\Cashtransaction;
use App\Models\Subcashtransaction;
use App\Models\Akun;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Collection;

class CapitalGoodsImport implements ToCollection, WithHeadingRow
{
    protected $results = [
        'successfulRows' => 0,
        'failedRows' => [],
    ];
    protected $staff;
    protected $date;
    protected $type;
    protected $description;

    public function __construct($staff, $date, $type = null, $description = null)
    {
        $this->staff = $staff;
        $this->date = $date;
        $this->type = $type;
        $this->description = $description;
    }

    public function collection(Collection $rows)
    {
        // Check if id_produk column exists in the imported data
        if (!isset($rows->first()['id_produk'])) {
            $this->results['failedRows'][] = [
                'row' => [],
                'error' => 'Column id_produk is required but missing in the import file'
            ];
            return;
        }

        // Validate all product IDs before processing
        $validProducts = 0;
        foreach ($rows as $row) {
            if (empty($row['qty'])) continue;
            
            if (Product::find($row['id_produk'])) {
                $validProducts++;
            } else {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => 'Product not found'
                ];
            }
        }

        // If no valid products found, reject the entire import
        if ($validProducts === 0) {
            $this->results['failedRows'][] = [
                'row' => [],
                'error' => 'No valid products found in the import file. Import process cancelled.'
            ];
            return;
        }

        $stock = new Stocktransaction;
        $stock->staff = $this->staff;
        $stock->date = date("Y-m-d", strtotime($this->date));
        $stock->type = $this->type;
        $stock->description = $this->description;
        $stock->nonmoney = 'in';
        $stock->save();

        $total = 0;

        foreach ($rows as $row) {
            if (empty($row['qty'])) {
                continue;
            }
            try {
                $product = Product::find($row['id_produk']);
                
                if (!$product) {
                    continue;
                }

                $sub = new Substocktransaction;
                $sub->stocktransaction_id = $stock->id;
                $sub->product_id = $product->id;
                $sub->qty = $row['qty'];
                $sub->purchase_price = $product->purchase_price;
                $sub->left = $row['qty'];
                $sub->total = $product->purchase_price * $row['qty'];
                $sub->save();

                $product->qty = $product->qty + $row['qty'];
                $product->save();

                $total += $sub->total;
                $this->results['successfulRows']++;

            } catch (\Exception $e) {
                $this->results['failedRows'][] = [
                    'row' => $row,
                    'error' => $e->getMessage()
                ];
            }
        }

        // Update Akun records
        $persediaan = Akun::where('name', '=', 'Persediaan Barang')->first();
        if ($persediaan) {
            $persediaan->total = $persediaan->total + $total;
            $persediaan->save();
        }

        $pendapatan = Akun::where('name', '=', 'Pendapatan Barang')->first();
        if ($pendapatan) {
            $pendapatan->total = $pendapatan->total + $total;
            $pendapatan->save();
        }

        // Update stock transaction total
        $stock->total = $total;
        $stock->save();
    }

    public function getResults()
    {
        return $this->results;
    }
}
