<?php

use App\Models\WalletTransaction;
use App\Models\SupportTicket; 
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\User;
use App\Models\Booking; 
use Illuminate\Support\Facades\Hash;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

// ==========================================
// 1. PUBLIC PAGES
// ==========================================
Route::get('/', function () { return view('login'); })->name('login'); 
Route::get('/signup', function () { return view('signup'); });
Route::get('/about', function () { return view('about'); });
Route::get('/contact', function () { return view('contact'); });


// ==========================================
// 2. AUTHENTICATION
// ==========================================
Route::post('/dummy-signup', function (Request $request) {
    $request->validate([
        'full_name' => 'required|string|max:255',
        'phone' => 'required|string|unique:users,phone|max:20',
        'password' => 'required|string|min:6',
    ]);

    User::create([
        'name' => $request->full_name,
        'phone' => $request->phone,
        'password' => Hash::make($request->password),
        'role' => 'technician',
        'status' => 'pending', 
    ]);
    return redirect('/');
});

Route::post('/dummy-login', function (Request $request) {
    $user = User::where('phone', $request->phone)->first();

    if (!$user || !Hash::check($request->password, $user->password)) {
        return response("<h2 style='text-align:center; margin-top:50px;'>Galat Phone Number ya Password!</h2>");
    }
    if ($user->status === 'pending') {
        return response("<h1 style='text-align:center; color:#eab308; margin-top:50px;'>Aapka account abhi PENDING hai.</h1>");
    }
    if ($user->status === 'blocked') {
        return response("<h1 style='text-align:center; color:red; margin-top:50px;'>Aapka account BLOCKED hai!</h1>");
    }

    Auth::login($user);

    if ($user->role === 'admin') { return redirect('/admin'); } 
    else { return redirect('/tech/dashboard'); }
});


// ==========================================
// 3. TECHNICIAN PANEL (SECURE ROUTES 🛡️)
// ==========================================
Route::middleware('auth')->group(function () {

    Route::get('/tech/dashboard', function () {
        $user = Auth::user(); 
        return view('technician.dashboard', compact('user'));
    });

    Route::get('/booking', function () { return view('technician.booking'); });

    Route::get('/support', function () { 
        $user = Auth::user();
        $tickets = SupportTicket::where('technician_id', $user->id)->latest()->take(5)->get();
        return view('technician.support', compact('user', 'tickets')); 
    });

    Route::get('/api/raise-ticket/{type}/{issue}', function($type, $issue) {
        $user = Auth::user();
        if($user) {
            SupportTicket::create([
                'technician_id' => $user->id,
                'type' => $type, 
                'issue' => urldecode($issue),
                'status' => 'open' 
            ]);
        }
        return response()->json(['success' => true]);
    });

    Route::get('/earnings', function () { 
        $user = Auth::user();
        
        $transactions = WalletTransaction::where('technician_id', $user->id)
                                         ->latest()
                                         ->get();
        
        $total_business = $transactions->where('type', 'earning')->sum('amount');
        $platform_fee = $transactions->where('type', 'commission')->sum('amount'); 
        $net_balance = $total_business + $platform_fee; 
        
        return view('technician.earnings', compact('user', 'transactions', 'total_business', 'platform_fee', 'net_balance')); 
    });

    Route::get('/track', function () { 
        $user = Auth::user();
        // 🚀 UPDATE: Sirf wahi jobs dikhao jo is technician ko assign hui hain, ya phir jo completed hain
        $dbJobs = Booking::where('technician_id', $user->id)->orWhere('status', 'completed')->latest()->get();
        
        $jobsForJs = $dbJobs->map(function($job) {
            return [
                'id' => 'IFX-' . $job->id,
                'customer' => $job->customer_name,
                'address' => $job->address,
                'status' => $job->status === 'pending' ? 'new' : $job->status, 
                'subStatus' => 'assigned',
                'otp' => '1234', 
                'paymentMode' => 'cash',
                'billItems' => [
                    ['id' => 's1', 'category' => 'Service', 'name' => $job->service_type, 'price' => $job->price]
                ]
            ];
        });
        
        return view('technician.track', ['jobsData' => $jobsForJs]); 
    });

    Route::get('/api/update-job/{id}/{status}', function($id, $status) {
        $dbId = str_replace('IFX-', '', $id); 
        $job = \App\Models\Booking::find($dbId);
        $user = Auth::user(); 
        
        if($job) {
            $job->status = $status;
            $job->save(); 
            
            if($status === 'completed') {
                $exists = WalletTransaction::where('booking_id', $id)->first();
                
                if(!$exists && $user) {
                    WalletTransaction::create([
                        'technician_id' => $user->id,
                        'booking_id' => $id,
                        'type' => 'earning',
                        'amount' => $job->price, 
                        'description' => $job->service_type . ' (Completed)'
                    ]);
                    
                    $commission = round($job->price * 0.15); 
                    WalletTransaction::create([
                        'technician_id' => $user->id,
                        'booking_id' => $id,
                        'type' => 'commission',
                        'amount' => -$commission, 
                        'description' => 'Platform Fee (15%)'
                    ]);
                }
            }
        }
        return response()->json(['success' => true]);
    });

});


// Test Job Route
Route::get('/create-test-job', function () {
    Booking::create([
        'customer_name' => 'Amit Sharma',
        'customer_phone' => '9876543210',
        'address' => 'Noida Sector 15',
        'service_type' => 'AC Gas Refill',
        'price' => 2200,
        'status' => 'pending'
    ]);
    return "Test job created!";
});


// ==========================================
// 4. ADMIN COMMAND CENTER
// ==========================================
Route::get('/admin', function () { return view('admin.dashboard'); });
Route::get('/admin/earnings', function () { return view('admin.earnings'); });
Route::get('/admin/tracking', function () { return view('admin.tracking'); });
Route::get('/admin/payouts', function () { return view('admin.payouts'); });

Route::get('/admin/jobs', function () { 
    $jobs = App\Models\Booking::latest()->get();
    $activeTechs = App\Models\User::where('role', 'technician')->where('status', 'active')->get();
    return view('admin.jobs', compact('jobs', 'activeTechs')); 
});

// 🚀 NAYA: API Route for assigning a job to a technician
Route::get('/api/admin/assign-job/{jobId}/{techId}', function ($jobId, $techId) {
    $job = App\Models\Booking::find($jobId);
    if($job) {
        $job->technician_id = $techId;
        $job->status = 'ongoing'; // Job seedha ongoing ho jayegi taaki tech ko dikhe
        $job->save();
        return response()->json(['success' => true]);
    }
    return response()->json(['success' => false], 400);
});

Route::get('/admin/technicians', function () { 
    $pendingTechs = User::where('role', 'technician')->where('status', 'pending')->get();
    $activeTechs = User::where('role', 'technician')->whereIn('status', ['active', 'blocked'])->get();
    return view('admin.technicians', compact('pendingTechs', 'activeTechs')); 
});

Route::get('/admin/approve-tech/{id}', function ($id) {
    $user = User::find($id);
    if($user) { $user->status = 'active'; $user->save(); }
    return redirect('/admin/technicians');
});

Route::get('/admin/toggle-block/{id}', function ($id) {
    $user = User::find($id);
    if($user) { $user->status = ($user->status === 'active') ? 'blocked' : 'active'; $user->save(); }
    return redirect('/admin/technicians');
});