<?php

namespace App\Controllers;

use App\Models\Station;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class StationController extends Controller
{
    public function index(Station $station)
    {
        $stations = Station::select('stations.*')
            ->selectRaw('(SELECT COUNT(*) FROM employee_station 
                        WHERE employee_station.station_id = stations.station_id 
                        AND employee_station.deleted_at IS NULL) as employees_count')
            ->withCount('payments')
            ->paginate(10);
        return view('stations.index', compact('stations'));
    }

    public function create()
    {
        return view('stations.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            // Basic Information
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:50|unique:stations,code',
            'status' => 'nullable|in:active,inactive,pending',
            
            // Location & Address
            'location' => 'required|string|max:255',
            'address' => 'nullable|string',
            'region' => 'nullable|string|max:100',
            
            // Contact Information
            'contact_person' => 'nullable|string|max:255',
            'contact_phone' => 'nullable|string|max:30',
            'contact_email' => 'nullable|email|max:255',
            'mobile_number' => 'nullable|string|max:30',
            
            // Financial Information
            'monthly_loss' => 'required|numeric',
            'deductions' => 'nullable|numeric',
            'opening_date' => 'nullable|date',
            
            // Additional Information
            'notes' => 'nullable|string',
        ]);

        $station = Station::create($validated);

        return redirect()->route('stations.index')->with('success', 'Station created successfully!');
    }

    public function show($id)
    {
        $station = Station::with([
            'serviceProviders',  
            'vendors',           
            'employees',
            'internetPayments',
            'airtimePayments',
            'paymentSchedules'
        ])->findOrFail($id);
        
        $stats = [
            'total_employees' => $station->employees->count(),
            'active_employees' => $station->employees->where('status', 'active')->count(),
            'total_internet_paid' => $station->internetPayments->where('status', 'paid')->sum('amount'),
            'total_airtime_paid' => $station->airtimePayments->where('status', 'active')->sum('amount'),
            'pending_payments' => $station->internetPayments->where('status', '!=', 'paid')->sum('amount'),
            'recent_payments_count' => $station->internetPayments->take(10)->count()
        ];
        
        return view('stations.show', compact('station', 'stats'));
    }

    public function edit(Station $station)
    {
        return view('stations.edit', compact('station'));
    }

    public function update(Request $request, Station $station)
    {
        $validated = $request->validate([
            // Basic Information
            'name' => 'required|string|max:255',
            'code' => 'nullable|string|max:50|unique:stations,code,' . $station->station_id . ',station_id',
            'status' => 'nullable|in:active,inactive,pending',
            
            // Location & Address
            'location' => 'required|string|max:255',
            'address' => 'nullable|string',
            'region' => 'nullable|string|max:100',
            
            // Contact Information
            'contact_person' => 'nullable|string|max:255',
            'contact_phone' => 'nullable|string|max:30',
            'contact_email' => 'nullable|email|max:255',
            'mobile_number' => 'nullable|string|max:30',
            
            // Financial Information
            'monthly_loss' => 'required|numeric',
            'deductions' => 'nullable|numeric',
            'opening_date' => 'nullable|date',
            
            // Additional Information
            'notes' => 'nullable|string',
        ]);

        $station->update($validated);

        return redirect()->route('stations.index')->with('success', 'Station updated successfully!');
    }

    public function destroy(Station $station)
    {
        try {
            $station->deleteWithRelations();
            return redirect()->route('stations.index')
                ->with('success', 'Station and all associated data deleted successfully!');
        } catch (\Exception $e) {
            Log::error('Failed to delete station ' . $station->station_id . ': ' . $e->getMessage());
            return redirect()->route('stations.index')
                ->with('error', 'Unable to delete station. Please try again later.');
        }
    }

    public function assignProvider(Request $request, $stationId)
    {
        try {
            $station = Station::findOrFail($stationId);
            
            $station->serviceProviders()->attach($request->provider_id, [
                'contract_number' => $request->contract_number,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'status' => $request->status ?? 'active'
            ]);
            
            return response()->json(['success' => true, 'message' => 'Provider assigned successfully']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function assignVendor(Request $request, $stationId)
    {
        try {
            $station = Station::findOrFail($stationId);
            
            $station->vendors()->attach($request->vendor_id, [
                'service_type' => $request->service_type,
                'contract_date' => $request->contract_date,
                'status' => $request->status ?? 'active'
            ]);
            
            return response()->json(['success' => true, 'message' => 'Vendor assigned successfully']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function getProviderAssignment($stationId, $providerId)
    {
        $station = Station::findOrFail($stationId);
        $assignment = $station->serviceProviders()
            ->where('internet_provider_id', $providerId)
            ->first();
        
        if (!$assignment) {
            return response()->json(['success' => false, 'message' => 'Assignment not found'], 404);
        }
        
        return response()->json([
            'success' => true,
            'data' => $assignment->pivot
        ]);
    }

    public function getVendorAssignment($stationId, $vendorId)
    {
        $station = Station::findOrFail($stationId);
        $assignment = $station->vendors()
            ->where('vendor_id', $vendorId)
            ->first();
        
        if (!$assignment) {
            return response()->json(['success' => false, 'message' => 'Assignment not found'], 404);
        }
        
        return response()->json([
            'success' => true,
            'data' => $assignment->pivot
        ]);
    }

    public function updateProviderAssignment(Request $request, $stationId, $providerId)
    {
        try {
            $station = Station::findOrFail($stationId);
            
            $station->serviceProviders()->updateExistingPivot($providerId, [
                'contract_number' => $request->contract_number,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'status' => $request->status
            ]);
            
            return response()->json(['success' => true, 'message' => 'Assignment updated successfully']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function updateVendorAssignment(Request $request, $stationId, $vendorId)
    {
        try {
            $station = Station::findOrFail($stationId);
            
            $station->vendors()->updateExistingPivot($vendorId, [
                'service_type' => $request->service_type,
                'contract_date' => $request->contract_date,
                'status' => $request->status
            ]);
            
            return response()->json(['success' => true, 'message' => 'Assignment updated successfully']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function removeProvider($stationId, $providerId)
    {
        try {
            $station = Station::findOrFail($stationId);
            $station->serviceProviders()->detach($providerId);
            
            return response()->json(['success' => true, 'message' => 'Provider removed successfully']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function removeVendor($stationId, $vendorId)
    {
        try {
            $station = Station::findOrFail($stationId);
            $station->vendors()->detach($vendorId);
            
            return response()->json(['success' => true, 'message' => 'Vendor removed successfully']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
    
}