<?php

namespace App\Http\Controllers;

use App\Models\ShipmentSupplier;
use App\Traits\ExcelUploadTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ShipmentSuppliersController extends Controller
{   
    use ExcelUploadTrait;   
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = ShipmentSupplier::select('m_shipment_suppliers.*')
                ->where('delete_flag', false);

            // Searching
            if ($request->has('search') && $request->search['value'] != '') {
                $search = $request->search['value'];
                $query->where(function ($q) use ($search) {
                    $q->where('code', 'ilike', "%{$search}%")
                        ->orWhere('name', 'ilike', "%{$search}%")
                        ->orWhere('contact_person', 'ilike', "%{$search}%")
                        ->orWhere('phone', 'ilike', "%{$search}%")
                        ->orWhere('email', 'ilike', "%{$search}%");
                });
            }

            $total = $query->count();

            // Sorting
            $columns = ['id', 'code', 'name', 'contact_person', 'phone', 'contact_days', 'lead_time_days', 'is_active'];
            $orderColumn = $columns[$request->order[0]['column']] ?? 'code';
            $orderDir = $request->order[0]['dir'] ?? 'asc';

            $query->orderBy($orderColumn, $orderDir);

            // Pagination
            $start = $request->start;
            $length = $request->length;
            $data = $query->skip($start)->take($length)->get();

            // Format data
            $result = [];
            $no = $start + 1;
            foreach ($data as $row) {
                $statusBadge = $row->is_active ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-secondary">Inactive</span>';
                $contactDays = $row->contact_days_string;
                $nextContact = $row->getNextContactDate();
                $nextContactStr = $nextContact ? $nextContact->format('D, M j Y') : '-';
                
                $result[] = [
                    $no++,
                    '<a href="' . route('shipment_suppliers.show', $row->id) . '">' . $row->code . '</a>',
                    $row->name,
                    $row->contact_person ?? '-',
                    $row->phone ?? '-',
                    $contactDays,
                    $row->lead_time_days . ' days',
                    $nextContactStr,
                    $statusBadge,
                ];
            }

            return response()->json([
                "draw" => intval($request->draw),
                "recordsTotal" => $total,
                "recordsFiltered" => $total,
                "data" => $result,
            ]);
        }

        return view('m-shipment-suppliers.index', [
            'variables' => $this->variables()
        ]);
    }

    public function create()
    {
        $variables['judul'] = 'Add Shipment Supplier';
        
        return view('m-shipment-suppliers.form', [
            'data' => json_decode(json_encode(array('id' => 0))),
            'variables' => $this->variables($variables)
        ]);
    }

    public function edit(ShipmentSupplier $shipmentSupplier)
    {
        $variables['judul'] = 'Edit Shipment Supplier';
        
        return view('m-shipment-suppliers.form', [
            'data' => $shipmentSupplier,
            'variables' => $this->variables($variables)
        ]);
    }

    public function store(Request $request, $prm_id = null)
    {
        $shipmentSupplier = null;
        if ($prm_id)
            $shipmentSupplier = ShipmentSupplier::findOrFail($prm_id);

        $rules = [
            'code' => $shipmentSupplier ? 
                'required|string|max:20|unique:m_shipment_suppliers,code,' . $shipmentSupplier->id . ',id,delete_flag,false' :
                'required|string|max:20|unique:m_shipment_suppliers,code,NULL,id,delete_flag,false',
            'name' => 'required|string|max:255',
            'contact_person' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
            'contact_days' => 'nullable|array',
            'contact_days.*' => 'in:monday,tuesday,wednesday,thursday,friday,saturday,sunday',
            'contact_time_start' => 'nullable|date_format:H:i',
            'contact_time_end' => 'nullable|date_format:H:i|after:contact_time_start',
            'lead_time_days' => 'nullable|integer|min:0|max:365',
            'notes' => 'nullable|string',
            'is_active' => 'boolean'
        ];

        $messages = [];
        $saveData = $request->validate($rules, $messages);

        // Set default values
        $saveData['contact_days'] = $saveData['contact_days'] ?? [];
        $saveData['lead_time_days'] = $saveData['lead_time_days'] ?? 1;
        $saveData['is_active'] = $request->has('is_active');

        try {
            if ($shipmentSupplier) {
                $shipmentSupplier->update(array_merge($saveData, [
                    'updated_by' => $this->logged_user_id,
                ]));
            } else {
                ShipmentSupplier::create(array_merge($saveData, [
                    'delete_flag' => false,
                    'created_by' => $this->logged_user_id,
                    'updated_by' => $this->logged_user_id,
                ]));
            }

            $notif = $shipmentSupplier ? 'Updated successfully.' : 'Successfully created.';
            return response()->json(['success', $notif]);
            
        } catch (\Exception $e) {
            $notif = $this->getErrorCatch($e->getMessage());
            return response()->json(['warning', $notif]);
        }
    }

    public function show(ShipmentSupplier $shipmentSupplier)
    {
        $shipmentSupplier->load(['creator', 'modificator']);
        $variables['judul'] = 'View Shipment Supplier: ' . $shipmentSupplier->code;
        return view('m-shipment-suppliers.show', [
            'data' => $shipmentSupplier,
            'variables' => $this->variables($variables)
        ]);
    }

    public function destroy(ShipmentSupplier $shipmentSupplier)
    {
        $shipmentSupplier->update([
            'delete_flag' => true,
            'updated_by' => $this->logged_user_id
        ]);

        return redirect()->route('shipment_suppliers.index')
            ->with('success', 'Successfully deleted');
    }

    // API method to get next contact info for supplier
    public function getContactInfo(Request $request)
    {
        $supplierId = $request->get('supplier_id');
        $supplier = ShipmentSupplier::find($supplierId);

        if (!$supplier) {
            return response()->json(['error' => 'Supplier not found'], 404);
        }

        $canContactToday = $supplier->canContactToday();
        $nextContactDate = $supplier->getNextContactDate();
        $estimatedDelivery = $supplier->getEstimatedDeliveryDate($nextContactDate);

        return response()->json([
            'supplier' => [
                'code' => $supplier->code,
                'name' => $supplier->name,
                'contact_person' => $supplier->contact_person,
                'phone' => $supplier->phone,
                'email' => $supplier->email,
            ],
            'contact_info' => [
                'can_contact_today' => $canContactToday,
                'contact_days' => $supplier->contact_days_string,
                'contact_window' => $supplier->contact_window,
                'next_contact_date' => $nextContactDate ? $nextContactDate->format('Y-m-d') : null,
                'next_contact_date_formatted' => $nextContactDate ? $nextContactDate->format('D, M j Y') : null,
                'lead_time_days' => $supplier->lead_time_days,
                'estimated_delivery' => $estimatedDelivery ? $estimatedDelivery->format('Y-m-d') : null,
                'estimated_delivery_formatted' => $estimatedDelivery ? $estimatedDelivery->format('D, M j Y') : null,
            ]
        ]);
    }

    private function variables($variables = [])
    {
        $defaultVariables = [
            'header_routes' => '
                <li class="breadcrumb-item">Master Data</li>
                <li class="breadcrumb-item active">Shipment Suppliers</li>
            ',
            'judul' => 'Shipment Suppliers'
        ];

        return array_merge($defaultVariables, $variables);
    }

    private function getErrorCatch($e)
    {
        if (strpos($e, '#error#') !== false) {
            $e = explode('#error#', $e);
            $e = $e[1];
        }

        return $e;
    }

    /**
     * Upload Excel untuk bulk insert/update shipment suppliers
     */
    public function uploadExcel(Request $request)
    {
        $request->validate([
            'excel_file' => 'required|mimes:xlsx,xls|max:10240',
        ]);

        try {
            $file = $request->file('excel_file');
            
            // Store uploaded file
            $uploadedFilePath = $this->storeUploadedExcel($file, 'shipment_suppliers');
            
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file->getRealPath());
            $sheet = $spreadsheet->getActiveSheet();
            $rows = $sheet->toArray();
            $rows = $this->trimExcelData($rows); // Trim all data to prevent whitespace issues

            // Remove header
            array_shift($rows);

            $inserted = 0;
            $updated = 0;
            $errors = [];
            $totalRows = count($rows);

            foreach ($rows as $index => $row) {
                $rowNumber = $index + 2;

                // Skip empty rows
                if (empty(array_filter($row))) {
                    continue;
                }

                try {
                    // Validate required fields
                    if (empty($row[0]) || empty($row[1])) {
                        $errors[] = ['row' => $rowNumber, 'error' => 'Code dan Name wajib diisi'];
                        continue;
                    }

                    $data = [
                        'code' => $row[0],
                        'name' => $row[1],
                        'address' => $row[2] ?? null,
                        'contact_person' => $row[3] ?? null,
                        'phone' => $row[4] ?? null,
                        'email' => $row[5] ?? null,
                        'delete_flag' => 0,
                        'updated_by' => auth()->id(),
                    ];

                    // Check if exists (by code)
                    $existing = \App\Models\ShipmentSupplier::where('code', $row[0])->first();

                    if ($existing) {
                        $existing->update($data);
                        $updated++;
                    } else {
                        $data['created_by'] = auth()->id();
                        \App\Models\ShipmentSupplier::create($data);
                        $inserted++;
                    }
                } catch (\Exception $e) {
                    $errors[] = ['row' => $rowNumber, 'error' => $e->getMessage()];
                }
            }

            // Log upload
            $errorCount = count($errors);
            \App\Models\ExcelUploadLog::create([
                'upload_type' => 'shipment_suppliers',
                'uploaded_file' => $uploadedFilePath,
                'original_filename' => $file->getClientOriginalName(),
                'total_rows' => $totalRows,
                'success_rows' => $inserted + $updated,
                'error_rows' => $errorCount,
                'error_details' => $errorCount > 0 ? json_encode($errors) : null,
                'status' => $errorCount > 0 ? ($inserted + $updated > 0 ? 'Partial' : 'Failed') : 'Success',
                'uploaded_by' => auth()->id(),
            ]);

            return response()->json([
                'success' => true,
                'message' => "Upload berhasil! Ditambahkan: {$inserted}, Diperbarui: {$updated}",
                'inserted' => $inserted,
                'updated' => $updated,
                'errors' => $errors,
                'uploaded_file' => $uploadedFilePath,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Upload gagal: ' . $e->getMessage(),
            ], 500);
        }
    }
    
    /**
     * Download template Excel untuk shipment suppliers
     */
    public function downloadTemplate()
    {
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Set header
        $sheet->setCellValue('A1', 'Code');
        $sheet->setCellValue('B1', 'Name');
        $sheet->setCellValue('C1', 'Address');
        $sheet->setCellValue('D1', 'Contact Person');
        $sheet->setCellValue('E1', 'Phone');
        $sheet->setCellValue('F1', 'Email');

        // Style header
        $headerStyle = [
            'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
            'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => 'F39C12']],
            'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER],
        ];
        $sheet->getStyle('A1:F1')->applyFromArray($headerStyle);

        // Set column width
        foreach (range('A', 'F') as $col) {
            $sheet->getColumnDimension($col)->setAutoSize(true);
        }

        // Add sample data
        $sheet->setCellValue('A2', 'SUP001');
        $sheet->setCellValue('B2', 'PT Supplier Utama');
        $sheet->setCellValue('C2', 'Jl. Industri No. 123');
        $sheet->setCellValue('D2', 'Budi Santoso');
        $sheet->setCellValue('E2', '021-1234567');
        $sheet->setCellValue('F2', 'budi@supplier.com');

        $sheet->setCellValue('A3', 'SUP002');
        $sheet->setCellValue('B3', 'CV Mitra Jaya');
        $sheet->setCellValue('C3', 'Jl. Raya Bekasi KM 20');
        $sheet->setCellValue('D3', 'Siti Aminah');
        $sheet->setCellValue('E3', '021-7654321');
        $sheet->setCellValue('F3', 'siti@mitrajaya.com');

        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $filename = 'template_shipment_suppliers_' . date('YmdHis') . '.xlsx';

        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;
    }
}
