<?php

namespace App\Http\Controllers\Master;

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

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

    public function index()
    {
        $title = "branch";
        $branches = Branch::orderBy('id', 'desc')->get();

        return view('master.branch', compact('title','branches'));
    }

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

        $branch = Branch::create([
            'name' => $request->input('name'),
            'address' => $request->input('address'),
            'phone' => $request->input('phone'),
            'is_active' => '1'
        ]);

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

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

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

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

    public function delete(Branch $branch)
    {
        $branch->delete();

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

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

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

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

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

        // Add example data
        $sheet->setCellValue('A2', 'Cabang Jakarta Pusat');
        $sheet->setCellValue('B2', 'Jl. Thamrin No. 1, Jakarta Pusat');
        $sheet->setCellValue('C2', '021-12345678');
        $sheet->setCellValue('A3', 'Cabang Bandung');
        $sheet->setCellValue('B3', 'Jl. Asia Afrika No. 10, Bandung');
        $sheet->setCellValue('C3', '022-87654321');

        // Create Excel file
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $fileName = 'template_import_cabang.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 cabang 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])) {
                    continue;
                }

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

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

                // Cek apakah cabang sudah ada
                $existingBranch = Branch::where('name', $branchName)->first();

                if ($existingBranch) {
                    // Update cabang yang sudah ada
                    $existingBranch->update([
                        'address' => $address,
                        'phone' => $phone
                    ]);
                    $successCount++;
                } else {
                    // Buat cabang baru
                    Branch::create([
                        'name' => $branchName,
                        'address' => $address,
                        'phone' => $phone,
                        'is_active' => '1'
                    ]);
                    $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('branch')->with('success', $message);
            } else {
                return redirect()->route('branch')->with('error', $message);
            }

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

}
