<?php

namespace App\Http\Controllers;

use App\Models\Asset;
use App\Models\Employee;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Storage;

class AssetController extends Controller
{
    public function index()
    {
        return view('assets.index');
    }

    public function getData(Request $request)
    {
        $query = Asset::with('employee');

        return DataTables::of($query)
            ->addColumn('photo_thumb', function ($asset) {
                if ($asset->photo) {
                    return '<img src="' . asset('storage/' . $asset->photo) . '" class="rounded" style="width: 50px; height: 50px; object-fit: cover;">';
                }
                return '<div class="bg-secondary rounded d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;"><i class="fas fa-box text-white"></i></div>';
            })
            ->addColumn('assigned_employee', function ($asset) {
                return $asset->employee ? $asset->employee->name : '<span class="text-muted">Unassigned</span>';
            })
            ->addColumn('status_badge', function ($asset) {
                $colors = [
                    'Available' => 'success',
                    'Assigned' => 'primary',
                    'Maintenance' => 'warning',
                    'Retired' => 'secondary'
                ];
                $color = $colors[$asset->status] ?? 'secondary';
                return '<span class="badge bg-' . $color . '">' . $asset->status . '</span>';
            })
            ->addColumn('warranty_badge', function ($asset) {
                $status = $asset->warrantyStatus();
                $colors = [
                    'Active' => 'success',
                    'Expiring Soon' => 'warning',
                    'Expired' => 'danger',
                    'N/A' => 'secondary'
                ];
                $color = $colors[$status] ?? 'secondary';
                return '<span class="badge bg-' . $color . '">' . $status . '</span>';
            })
            ->addColumn('action', function ($asset) {
                $btn = '<div class="d-flex gap-1 justify-content-center">';
                
                $btn .= '<a href="javascript:void(0)" class="btn-crm-view view-asset-btn" data-id="' . $asset->id . '" title="View Details">
                            <i class="fas fa-eye"></i>
                        </a>';

                if (auth()->user()->canAccess('assets.manage')) {
                    $btn .= '<a href="' . route('assets.edit', $asset->id) . '" class="btn-crm-edit" title="Edit Asset">
                                <i class="fas fa-edit"></i>
                            </a>';
                    
                    $btn .= '<button class="btn-crm-delete delete-asset" data-id="' . $asset->id . '" title="Delete Asset">
                                <i class="fas fa-trash"></i>
                            </button>';
                }

                $btn .= '</div>';
                return $btn;
            })

            ->rawColumns(['photo_thumb', 'assigned_employee', 'status_badge', 'warranty_badge', 'action'])
            ->make(true);
    }

    public function create()
    {
        $employees = Employee::orderBy('name')->get();
        $assetId = Asset::generateAssetId();
        return view('assets.create', compact('employees', 'assetId'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'asset_id' => 'required|unique:assets,asset_id',
            'name' => 'required|string|max:255',
            'serial_number' => 'required|unique:assets,serial_number',
            'purchase_date' => 'required|date',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'category' => 'nullable|string',
            'warranty_expiry' => 'nullable|date',
            'purchase_price' => 'nullable|numeric',
            'vendor' => 'nullable|string',
            'status' => 'required|in:Available,Assigned,Maintenance,Retired',
            'assigned_to' => 'nullable|exists:employees,id'
        ]);

        $data = $request->except('photo');

        // Handle photo upload
        if ($request->hasFile('photo')) {
            $photo = $request->file('photo');
            $filename = time() . '_' . $photo->getClientOriginalName();
            $path = $photo->storeAs('assets', $filename, 'public');
            $data['photo'] = $path;
        }

        // Set assigned date if assigning
        if ($request->assigned_to) {
            $data['assigned_date'] = now();
            $data['status'] = 'Assigned';
        }

        Asset::create($data);

        return redirect()->route('assets.index')->with('success', 'Asset created successfully.');
    }

    public function show($id)
    {
        $asset = Asset::with('employee')->findOrFail($id);
        $asset->warranty_status = $asset->warrantyStatus();
        return response()->json($asset);
    }

    public function edit(Asset $asset)
    {
        $employees = Employee::orderBy('name')->get();
        return view('assets.edit', compact('asset', 'employees'));
    }

    public function update(Request $request, Asset $asset)
    {
        $request->validate([
            'asset_id' => 'required|unique:assets,asset_id,' . $asset->id,
            'name' => 'required|string|max:255',
            'serial_number' => 'required|unique:assets,serial_number,' . $asset->id,
            'purchase_date' => 'required|date',
            'photo' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'category' => 'nullable|string',
            'warranty_expiry' => 'nullable|date',
            'purchase_price' => 'nullable|numeric',
            'vendor' => 'nullable|string',
            'status' => 'required|in:Available,Assigned,Maintenance,Retired',
            'assigned_to' => 'nullable|exists:employees,id'
        ]);

        $data = $request->except('photo');

        // Handle photo upload
        if ($request->hasFile('photo')) {
            // Delete old photo
            if ($asset->photo) {
                Storage::disk('public')->delete($asset->photo);
            }

            $photo = $request->file('photo');
            $filename = time() . '_' . $photo->getClientOriginalName();
            $path = $photo->storeAs('assets', $filename, 'public');
            $data['photo'] = $path;
        }

        // Update assigned date if assigning for first time
        if ($request->assigned_to && !$asset->assigned_to) {
            $data['assigned_date'] = now();
        }

        // Clear assigned date if unassigning
        if (!$request->assigned_to && $asset->assigned_to) {
            $data['assigned_date'] = null;
        }

        $asset->update($data);

        return redirect()->route('assets.index')->with('success', 'Asset updated successfully.');
    }

    public function destroy(Asset $asset)
    {
        // Delete photo if exists
        if ($asset->photo) {
            Storage::disk('public')->delete($asset->photo);
        }

        $asset->delete();

        return response()->json(['success' => 'Asset deleted successfully.']);
    }

    public function assign(Request $request, $id)
    {
        $request->validate([
            'employee_id' => 'required|exists:employees,id'
        ]);

        $asset = Asset::findOrFail($id);
        $asset->update([
            'assigned_to' => $request->employee_id,
            'assigned_date' => now(),
            'status' => 'Assigned'
        ]);

        return response()->json(['success' => 'Asset assigned successfully.']);
    }

    public function unassign($id)
    {
        $asset = Asset::findOrFail($id);
        $asset->update([
            'assigned_to' => null,
            'assigned_date' => null,
            'status' => 'Available'
        ]);

        return response()->json(['success' => 'Asset unassigned successfully.']);
    }
}
