<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Carbon\Carbon;
use App\Models\Customer;
use App\Models\Product;
use App\Models\ProductPrice;
use App\Models\Supplier;
use App\Models\Branch;

// Class Internal untuk Membaca Excel
class GenericImport implements ToArray {
    public function array(array $array) {}
}

// Class Internal untuk Mendownload Template Excel
class TemplateExport implements FromArray, WithHeadings {
    protected $headers;

    public function __construct(array $headers) {
        $this->headers = $headers;
    }

    public function headings(): array {
        return $this->headers;
    }

    public function array(): array {
        return []; // Kita hanya butuh Header, baris data dikosongkan
    }
}

class ImportExportController extends Controller
{
    /**
     * DOWNLOAD TEMPLATE EXCEL UNIVERSAL
     */
    public function downloadTemplate($type)
    {
        $headers = [];
        $filename = '';

        if ($type === 'customers') {
            $headers = ['Nama Toko (Wajib)', 'Nama Pemilik', 'No HP', 'Alamat', 'Limit Kredit (Angka)', 'Termin (Hari)', 'Level Harga (1/2/3/4)'];
            $filename = 'Template_Pelanggan.xlsx';
        } elseif ($type === 'products') {
            // PERBAIKAN: Menambahkan Kolom Tipe Produk
            $headers = ['Nama Produk Induk (Wajib)', 'Kategori ID', 'SKU (Kosongkan=Auto)', 'Harga Beli (HPP)', 'Satuan Dasar (Contoh: PCS)', 'Harga Jual Level 1', 'Tipe (trading / raw_material / consumable / finished_good)'];
            $filename = 'Template_Produk.xlsx';
        } elseif ($type === 'suppliers') {
            $headers = ['Nama Supplier (Wajib)', 'Email', 'No HP', 'Alamat Lengkap'];
            $filename = 'Template_Supplier.xlsx';
        } else {
            return response()->json(['message' => 'Tipe tidak valid'], 400);
        }

        return Excel::download(new TemplateExport($headers), $filename);
    }

    /**
     * PROSES UPLOAD EXCEL MAATWEBSITE
     */
    public function uploadExcel(Request $request, $type)
    {
        $request->validate(['file' => 'required|file|mimes:xlsx,xls']);

        try {
            DB::beginTransaction();
            $user = auth()->user();
            $branchId = ($user->role === 'owner') ? ($user->branch_id ?? 1) : $user->branch_id;

            $data = Excel::toArray(new GenericImport, $request->file('file'));
            if (empty($data) || empty($data[0])) {
                throw new \Exception("File kosong atau format tidak valid.");
            }

            // $data[0] adalah Sheet pertama dari Excel
            $rows = $data[0];
            array_shift($rows); // Hapus baris pertama (Header) agar tidak ikut terinput
            
            $count = 0;

            if ($type === 'customers') {
                $branch = Branch::find($branchId);
                $branchCode = isset($branch->code) ? substr(strtoupper($branch->code), 0, 2) : 'GN';

                foreach ($rows as $row) {
                    if (empty($row[0])) continue; // Lewati jika nama kosong

                    $totalCust = Customer::where('branch_id', $branchId)->count() + 1;
                    $customerCode = $branchCode . str_pad($totalCust, 6, '0', STR_PAD_LEFT);

                    Customer::create([
                        'customer_code' => $customerCode,
                        'name' => strtoupper(trim($row[0])),
                        'owner_name' => strtoupper(trim($row[1] ?? '')),
                        'phone' => trim($row[2] ?? ''),
                        'address' => trim($row[3] ?? ''),
                        'credit_limit' => (float)($row[4] ?? 0),
                        'due_days' => (int)($row[5] ?? 0),
                        'price_level' => trim($row[6] ?? '1'),
                        'branch_id' => $branchId,
                        'is_active' => true,
                        'registration_status' => 'approved',
                        'is_pkp' => false,
                        'default_tax_method' => 'include'
                    ]);
                    $count++;
                }

            } elseif ($type === 'products') {
                foreach ($rows as $row) {
                    if (empty($row[0])) continue; // Wajib ada Nama Produk

                    // Analisa Tipe Produk (Default: trading)
                    $rawType = strtolower(trim($row[6] ?? 'trading'));
                    $validTypes = ['trading', 'raw_material', 'finished_good','consumable'];
                    $productType = in_array($rawType, $validTypes) ? $rawType : 'trading';

                    // PERBAIKAN: Jika bukan bahan baku dan bahan penolong, harga jual L1 wajib ada. Jika kosong, lewati baris ini.
                    if (!in_array($productType, ['raw_material', 'consumable']) && empty($row[5])) {
                        continue;
                    }

                    $sku = !empty(trim($row[2])) ? trim($row[2]) : 'BRG' . date('ymd') . mt_rand(1000, 9999);
                    $buyPrice = (float)($row[3] ?? 0);
                    
                    $product = Product::create([
                        'name' => strtoupper(trim($row[0])),
                        'category_id' => (int)($row[1] ?? 1),
                        'sku' => $sku,
                        'buy_price' => $buyPrice,
                        'average_cost' => $buyPrice, // PERBAIKAN: Set HPP awal sesuai harga beli di excel
                        'unit' => strtoupper(trim($row[4] ?? 'PCS')),
                        'product_type' => $productType, // <--- TAMBAHAN: Menyimpan Tipe Produk
                        'is_active' => true,
                        'is_available_online' => true,
                    ]);

                    // Mengaitkan Produk ke Cabang Admin saat ini
                    $product->branches()->sync([$branchId]);

                    // Memasukkan Harga Jual Level 1 (Hanya jika diisi nilainya > 0)
                    $sellPrice = (float)($row[5] ?? 0);
                    if ($sellPrice > 0) {
                        ProductPrice::create([
                            'product_id' => $product->id,
                            'level' => '1',
                            'unit_level' => 1,
                            'amount' => $sellPrice
                        ]);
                        // Duplikasi untuk standar sistem _user (API Mobile)
                        ProductPrice::create([
                            'product_id' => $product->id,
                            'level' => '1_user',
                            'unit_level' => 1,
                            'amount' => $sellPrice
                        ]);
                    }

                    $count++;
                }

            } elseif ($type === 'suppliers') {
                foreach ($rows as $row) {
                    if (empty($row[0])) continue;

                    Supplier::create([
                        'name' => strtoupper(trim($row[0])),
                        'email' => trim($row[1] ?? ''),
                        'phone' => trim($row[2] ?? ''),
                        'address' => trim($row[3] ?? ''),
                    ]);
                    $count++;
                }
            } else {
                throw new \Exception("Tipe import tidak dikenali.");
            }

            DB::commit();
            return response()->json(['success' => true, 'count' => $count]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }
}