<?php

namespace App\Http\Controllers\Master;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Supplier;

class SuppliersController extends Controller
{
    public function __construct()
    {
        $this->middleware(['permission:suppliers.index'])->only('index');
        $this->middleware(['permission:suppliers.create'])->only('save');
        $this->middleware(['permission:suppliers.edit'])->only('update');
        $this->middleware(['permission:suppliers.delete'])->only('delete');
    }

    public function index()
    {
        $title = "supplier";
        $suppliers = Supplier::orderBy('id', 'desc')->get();

        return view('master.supplier', compact('title','suppliers'));
    }

    public function save(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:suppliers'
        ]);

        $supplier = Supplier::create([
            'name' => $request->input('name'),
            'phone' => $request->input('phone'),
            'address' => $request->input('address'),
            'email' => $request->input('email'),
        ]);

        if($supplier){
            //redirect dengan pesan sukses
            return redirect()->route('supplier')->with(['success' => 'Data Berhasil Disimpan!']);
        }else{
            //redirect dengan pesan error
            return redirect()->route('supplier')->with(['error' => 'Data Gagal Disimpan!']);
        }
    }

    public function update(Request $request, Supplier $supplier)
    {
        $this->validate($request, [
            'name' => 'required|unique:suppliers,name,'.$supplier->id
        ]);

        $supplier = Supplier::findOrFail($supplier->id);
        $supplier->update([
            'name' => $request->input('name'),
            'phone' => $request->input('phone'),
            'address' => $request->input('address'),
            'email' => $request->input('email')
        ]);

        if($supplier){
            //redirect dengan pesan sukses
            return redirect()->route('supplier')->with(['success' => 'Data Berhasil Disimpan!']);
        }else{
            //redirect dengan pesan error
            return redirect()->route('supplier')->with(['error' => 'Data Gagal Disimpan!']);
        }
    }

    public function delete(Supplier $supplier)
    {
        $supplier->delete();

        return redirect()->route('supplier')->with('success', 'Data Berhasil Dihapus');
    }

    /**
     * Download template Excel untuk import supplier
     */
    public function downloadTemplate()
    {
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Set header
        $sheet->setCellValue('A1', 'Nama Supplier');
        $sheet->setCellValue('B1', 'No. Telepon');
        $sheet->setCellValue('C1', 'Email');
        $sheet->setCellValue('D1', 'Alamat');

        // Style header
        $sheet->getStyle('A1:D1')->getFont()->setBold(true);
        $sheet->getStyle('A1:D1')->getFill()
            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
            ->getStartColor()->setARGB('FFCCCCCC');

        // Set column width
        $sheet->getColumnDimension('A')->setWidth(30);
        $sheet->getColumnDimension('B')->setWidth(20);
        $sheet->getColumnDimension('C')->setWidth(30);
        $sheet->getColumnDimension('D')->setWidth(50);

        // Add example data
        $sheet->setCellValue('A2', 'Contoh Supplier 1');
        $sheet->setCellValue('B2', '081234567890');
        $sheet->setCellValue('C2', 'supplier1@example.com');
        $sheet->setCellValue('D2', 'Jl. Contoh No. 123, Jakarta');
        $sheet->setCellValue('A3', 'Contoh Supplier 2');
        $sheet->setCellValue('B3', '081234567891');
        $sheet->setCellValue('C3', 'supplier2@example.com');
        $sheet->setCellValue('D3', 'Jl. Contoh No. 456, Bandung');

        // Create Excel file
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $fileName = 'template_import_supplier.xlsx';

        // Set headers for download
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $writer->save('php://output');
        exit;
    }

    /**
     * Import supplier dari Excel
     */
    public function importExcel(Request $request)
    {
        $this->validate($request, [
            'excel_file' => 'required|mimes:xlsx,xls|max:2048',
        ]);

        try {
            $file = $request->file('excel_file');
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file->getPathname());
            $sheet = $spreadsheet->getActiveSheet();
            $rows = $sheet->toArray();

            // Cek apakah file kosong
            if (count($rows) < 2) {
                return redirect()->back()->with('error', 'File Excel kosong atau format tidak sesuai!');
            }

            $successCount = 0;
            $errorCount = 0;
            $errors = [];

            // Mulai dari baris 2 (index 1) - setelah header
            for ($i = 1; $i < count($rows); $i++) {
                $row = $rows[$i];

                // Skip jika baris kosong
                if (empty($row[0]) && empty($row[1]) && empty($row[2]) && empty($row[3])) {
                    continue;
                }

                $rowNumber = $i + 1;
                $supplierName = isset($row[0]) ? trim($row[0]) : '';
                $phone = isset($row[1]) ? trim($row[1]) : '';
                $email = isset($row[2]) ? trim($row[2]) : '';
                $address = isset($row[3]) ? trim($row[3]) : '';

                // Validasi data wajib
                if (empty($supplierName)) {
                    $errors[] = "Baris {$rowNumber}: Nama supplier tidak boleh kosong";
                    $errorCount++;
                    continue;
                }

                // Cek apakah supplier sudah ada
                $existingSupplier = Supplier::where('name', $supplierName)->first();

                if ($existingSupplier) {
                    // Update supplier yang sudah ada
                    $existingSupplier->update([
                        'phone' => $phone,
                        'email' => $email,
                        'address' => $address
                    ]);
                    $successCount++;
                } else {
                    // Buat supplier baru
                    Supplier::create([
                        'name' => $supplierName,
                        'phone' => $phone,
                        'email' => $email,
                        'address' => $address
                    ]);
                    $successCount++;
                }
            }

            $message = "Import selesai! Berhasil: {$successCount}, Gagal: {$errorCount}";

            if ($errorCount > 0) {
                $message .= "\n\nDetail error:\n" . implode("\n", array_slice($errors, 0, 10));
                if (count($errors) > 10) {
                    $message .= "\n... dan " . (count($errors) - 10) . " error lainnya";
                }
            }

            if ($successCount > 0) {
                return redirect()->route('supplier')->with('success', $message);
            } else {
                return redirect()->route('supplier')->with('error', $message);
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Gagal import Excel: ' . $e->getMessage());
        }
    }

}
