<?php
// app/Http/Controllers/Admin/WarehouseController.php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Warehouse;
use App\Models\User;
use App\Models\CommissionRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class WarehouseController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth', 'verified', 'role:admin']);
    }

    /**
     * Display a listing of warehouses
     */
    public function index(Request $request)
    {
        $query = Warehouse::withCount(['users', 'commissionRates']);

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('code', 'like', "%{$search}%")
                  ->orWhere('name', 'like', "%{$search}%")
                  ->orWhere('location', 'like', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $isActive = $request->status === 'active';
            $query->where('is_active', $isActive);
        }

        $warehouses = $query->orderBy('created_at', 'desc')->paginate(20);

        // Statistics
        $allWarehouses = Warehouse::withCount(['users', 'commissionRates'])->get();
        $stats = [
            'total' => $allWarehouses->count(),
            'active' => $allWarehouses->where('is_active', true)->count(),
            'inactive' => $allWarehouses->where('is_active', false)->count(),
            'with_users' => $allWarehouses->where('users_count', '>', 0)->count(),
            'with_rates' => $allWarehouses->where('commission_rates_count', '>', 0)->count(),
        ];

        return view('admin.warehouses.index', compact('warehouses', 'stats'));
    }

    /**
     * Show the form for creating a new warehouse
     */
    public function create()
    {
        return view('admin.warehouses.create');
    }

    /**
     * Store a newly created warehouse
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'code' => 'required|string|max:10|unique:warehouses,code|regex:/^[A-Z0-9]+$/',
            'name' => 'required|string|max:255',
            'location' => 'nullable|string|max:1000',
            'is_active' => 'required|boolean',
        ], [
            'code.required' => 'กรุณาระบุรหัสคลัง',
            'code.unique' => 'รหัสคลังนี้ถูกใช้งานแล้ว',
            'code.regex' => 'รหัสคลังต้องเป็นตัวอักษรพิมพ์ใหญ่และตัวเลขเท่านั้น',
            'code.max' => 'รหัสคลังต้องไม่เกิน 10 ตัวอักษร',
            'name.required' => 'กรุณาระบุชื่อคลัง',
            'name.max' => 'ชื่อคลังต้องไม่เกิน 255 ตัวอักษร',
            'location.max' => 'ที่อยู่ต้องไม่เกิน 1000 ตัวอักษร',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        try {
            Warehouse::create([
                'code' => strtoupper($request->code),
                'name' => $request->name,
                'location' => $request->location,
                'is_active' => $request->boolean('is_active', true),
            ]);

            return redirect()
                ->route('admin.warehouses.index')
                ->with('success', 'เพิ่มคลังสินค้าใหม่เรียบร้อยแล้ว');

        } catch (\Exception $e) {
            return back()
                ->withErrors(['error' => 'เกิดข้อผิดพลาดในการสร้างคลัง: ' . $e->getMessage()])
                ->withInput();
        }
    }

    /**
     * Display the specified warehouse
     */
    public function show(Warehouse $warehouse)
    {
        $warehouse->load(['users', 'commissionRates']);

        // Get statistics for this warehouse
        $stats = [
            'total_users' => $warehouse->users->count(),
            'active_users' => $warehouse->users->where('is_active', true)->count(),
            'vehicle_2wheel' => $warehouse->users->where('role', '2wheel')->count(),
            'vehicle_4wheel' => $warehouse->users->where('role', '4wheel')->count(),
            'commission_rates' => $warehouse->commissionRates->count(),
            'active_rates' => $warehouse->commissionRates->where('is_active', true)->count(),
        ];

        return view('admin.warehouses.show', compact('warehouse', 'stats'));
    }

    /**
     * Show the form for editing the specified warehouse
     */
    public function edit(Warehouse $warehouse)
    {
        return view('admin.warehouses.edit', compact('warehouse'));
    }

    /**
     * Update the specified warehouse
     */
    public function update(Request $request, Warehouse $warehouse)
    {
        $validator = Validator::make($request->all(), [
            'code' => [
                'required',
                'string',
                'max:10',
                'regex:/^[A-Z0-9]+$/',
                Rule::unique('warehouses')->ignore($warehouse->id),
            ],
            'name' => 'required|string|max:255',
            'location' => 'nullable|string|max:1000',
            'is_active' => 'required|boolean',
        ], [
            'code.required' => 'กรุณาระบุรหัสคลัง',
            'code.unique' => 'รหัสคลังนี้ถูกใช้งานแล้ว',
            'code.regex' => 'รหัสคลังต้องเป็นตัวอักษรพิมพ์ใหญ่และตัวเลขเท่านั้น',
            'code.max' => 'รหัสคลังต้องไม่เกิน 10 ตัวอักษร',
            'name.required' => 'กรุณาระบุชื่อคลัง',
            'name.max' => 'ชื่อคลังต้องไม่เกิน 255 ตัวอักษร',
            'location.max' => 'ที่อยู่ต้องไม่เกิน 1000 ตัวอักษร',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        try {
            $oldCode = $warehouse->code;
            $newCode = strtoupper($request->code);

            $warehouse->update([
                'code' => $newCode,
                'name' => $request->name,
                'location' => $request->location,
                'is_active' => $request->boolean('is_active'),
            ]);

            // If warehouse code changed, update related users and commission rates
            if ($oldCode !== $newCode) {
                // Update users
                User::where('warehouse_code', $oldCode)
                    ->update(['warehouse_code' => $newCode]);

                // Update commission rates
                CommissionRate::where('warehouse_code', $oldCode)
                    ->update(['warehouse_code' => $newCode]);
            }

            return redirect()
                ->route('admin.warehouses.index')
                ->with('success', 'อัปเดตข้อมูลคลังสินค้าเรียบร้อยแล้ว');

        } catch (\Exception $e) {
            return back()
                ->withErrors(['error' => 'เกิดข้อผิดพลาดในการอัปเดต: ' . $e->getMessage()])
                ->withInput();
        }
    }

    /**
     * Remove the specified warehouse
     */
    public function destroy(Warehouse $warehouse)
    {
        // Check if warehouse has users
        $userCount = $warehouse->users()->count();
        if ($userCount > 0) {
            return response()->json([
                'success' => false,
                'message' => "ไม่สามารถลบคลังที่มีผู้ใช้งาน ({$userCount} คน) ได้"
            ]);
        }

        // Check if warehouse has delivery records through users
        $hasDeliveryRecords = User::where('warehouse_code', $warehouse->code)
            ->whereHas('deliveryRecords')
            ->exists();

        if ($hasDeliveryRecords) {
            return response()->json([
                'success' => false,
                'message' => 'ไม่สามารถลบคลังที่มีประวัติการจัดส่งได้'
            ]);
        }

        try {
            // Delete related commission rates first
            CommissionRate::where('warehouse_code', $warehouse->code)->delete();

            // Delete warehouse
            $warehouse->delete();

            return response()->json([
                'success' => true,
                'message' => 'ลบคลังสินค้าเรียบร้อยแล้ว'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'เกิดข้อผิดพลาดในการลบ: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Toggle warehouse status
     */
    public function toggle(Warehouse $warehouse)
    {
        try {
            $warehouse->update([
                'is_active' => !$warehouse->is_active
            ]);

            $status = $warehouse->is_active ? 'เปิดใช้งาน' : 'ปิดใช้งาน';

            return response()->json([
                'success' => true,
                'message' => "เปลี่ยนสถานะคลังเป็น {$status} เรียบร้อยแล้ว"
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'เกิดข้อผิดพลาดในการเปลี่ยนสถานะ: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Bulk operations for warehouses
     */
    public function bulk(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'action' => 'required|in:activate,deactivate,delete',
            'warehouse_ids' => 'required|array|min:1',
            'warehouse_ids.*' => 'exists:warehouses,id',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'ข้อมูลไม่ถูกต้อง'
            ]);
        }

        $warehouseIds = $request->warehouse_ids;
        $action = $request->action;

        try {
            $count = 0;

            switch ($action) {
                case 'activate':
                    $count = Warehouse::whereIn('id', $warehouseIds)->update(['is_active' => true]);
                    break;

                case 'deactivate':
                    $count = Warehouse::whereIn('id', $warehouseIds)->update(['is_active' => false]);
                    break;

                case 'delete':
                    // Check for warehouses with users or delivery records
                    $warehousesWithUsers = Warehouse::whereIn('id', $warehouseIds)
                        ->whereHas('users')
                        ->count();
                    
                    if ($warehousesWithUsers > 0) {
                        return response()->json([
                            'success' => false,
                            'message' => 'ไม่สามารถลบคลังที่มีผู้ใช้งานได้'
                        ]);
                    }

                    // Delete related commission rates first
                    $warehouseCodes = Warehouse::whereIn('id', $warehouseIds)->pluck('code');
                    CommissionRate::whereIn('warehouse_code', $warehouseCodes)->delete();

                    $count = Warehouse::whereIn('id', $warehouseIds)->delete();
                    break;
            }

            $actionText = [
                'activate' => 'เปิดใช้งาน',
                'deactivate' => 'ปิดใช้งาน',
                'delete' => 'ลบ'
            ];

            return response()->json([
                'success' => true,
                'message' => "{$actionText[$action]} {$count} รายการเรียบร้อยแล้ว",
                'affected' => $count
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'เกิดข้อผิดพลาด: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Export warehouses to CSV
     */
    public function export(Request $request)
    {
        try {
            $query = Warehouse::withCount(['users', 'commissionRates']);

            // Apply same filters as index
            if ($request->filled('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('code', 'like', "%{$search}%")
                      ->orWhere('name', 'like', "%{$search}%")
                      ->orWhere('location', 'like', "%{$search}%");
                });
            }

            if ($request->filled('status')) {
                $isActive = $request->status === 'active';
                $query->where('is_active', $isActive);
            }

            $warehouses = $query->orderBy('created_at', 'desc')->get();

            $filename = 'warehouses_' . date('Y-m-d_H-i-s') . '.csv';
            
            $headers = [
                'Content-Type' => 'text/csv',
                'Content-Disposition' => "attachment; filename=\"{$filename}\"",
            ];

            $callback = function() use ($warehouses) {
                $file = fopen('php://output', 'w');
                
                // UTF-8 BOM for proper Thai character display in Excel
                fwrite($file, "\xEF\xBB\xBF");
                
                // Headers
                fputcsv($file, [
                    'ID',
                    'รหัสคลัง',
                    'ชื่อคลัง',
                    'ที่อยู่',
                    'จำนวนผู้ใช้',
                    'จำนวนอัตราค่าคอมมิชชั่น',
                    'สถานะ',
                    'สร้างเมื่อ',
                    'อัปเดตเมื่อ'
                ]);

                // Data rows
                foreach ($warehouses as $warehouse) {
                    fputcsv($file, [
                        $warehouse->id,
                        $warehouse->code,
                        $warehouse->name,
                        $warehouse->location ?? '',
                        $warehouse->users_count,
                        $warehouse->commission_rates_count,
                        $warehouse->is_active ? 'ใช้งานอยู่' : 'ปิดใช้งาน',
                        $warehouse->created_at ? $warehouse->created_at->format('d/m/Y H:i:s') : '',
                        $warehouse->updated_at ? $warehouse->updated_at->format('d/m/Y H:i:s') : '',
                    ]);
                }

                fclose($file);
            };

            return response()->stream($callback, 200, $headers);

        } catch (\Exception $e) {
            return back()->with('error', 'เกิดข้อผิดพลาดในการส่งออกข้อมูล: ' . $e->getMessage());
        }
    }

    /**
     * Get warehouse statistics for AJAX requests
     */
    public function getStats(Warehouse $warehouse)
    {
        try {
            $warehouse->load(['users', 'commissionRates']);

            $stats = [
                'total_users' => $warehouse->users->count(),
                'active_users' => $warehouse->users->where('is_active', true)->count(),
                'vehicle_2wheel' => $warehouse->users->where('role', '2wheel')->count(),
                'vehicle_4wheel' => $warehouse->users->where('role', '4wheel')->count(),
                'commission_rates' => $warehouse->commissionRates->count(),
                'active_rates' => $warehouse->commissionRates->where('is_active', true)->count(),
            ];

            return response()->json([
                'success' => true,
                'stats' => $stats
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'เกิดข้อผิดพลาด: ' . $e->getMessage()
            ]);
        }
    }
}