<?php

namespace App\Controllers;
use Config\Database;

class Flights extends BaseController
{
    public function index()
    {
        $db = Database::connect();
        $source = $this->request->getGet('source');
        $destination = $this->request->getGet('destination');
        
        // Mock query if DB is loaded
        $builder = $db->table('flights');
        if ($source && $destination) {
            $builder->like('source', $source, 'both');
            $builder->like('destination', $destination, 'both');
        }
        
        $data['flights'] = []; // Array of flights
        
        try {
            $data['flights'] = $builder->get()->getResult();
        } catch (\Exception $e) {
            // Fallback mock data if DB isn't seeded/exists
            if(empty($data['flights'])) {
                $data['flights'] = [
                    (object)[
                        'id' => 1,
                        'airline' => 'IndiGo',
                        'flight_number' => '6E-101',
                        'source' => $source ?: 'Delhi',
                        'destination' => $destination ?: 'Mumbai',
                        'departure_time' => date('Y-m-d H:i:s', strtotime('+1 day 10:00:00')),
                        'arrival_time' => date('Y-m-d H:i:s', strtotime('+1 day 12:30:00')),
                        'base_price' => 4500.00
                    ],
                    (object)[
                        'id' => 2,
                        'airline' => 'Air India',
                        'flight_number' => 'AI-302',
                        'source' => $source ?: 'Delhi',
                        'destination' => $destination ?: 'Mumbai',
                        'departure_time' => date('Y-m-d H:i:s', strtotime('+1 day 14:00:00')),
                        'arrival_time' => date('Y-m-d H:i:s', strtotime('+1 day 16:15:00')),
                        'base_price' => 5500.00
                    ],
                     (object)[
                        'id' => 3,
                        'airline' => 'Vistara',
                        'flight_number' => 'UK-955',
                        'source' => $source ?: 'Delhi',
                        'destination' => $destination ?: 'Mumbai',
                        'departure_time' => date('Y-m-d H:i:s', strtotime('+2 days 08:00:00')),
                        'arrival_time' => date('Y-m-d H:i:s', strtotime('+2 days 10:30:00')),
                        'base_price' => 6200.00
                    ]
                ];
            }
        }
        
        $data['title'] = 'Search Flights';
        return view('flights/index', $data);
    }
}
