<?php

namespace App\Controllers;

class Checkout extends BaseController
{
    public function index()
    {
        if (!session()->get('isLoggedIn')) {
            session()->setFlashdata('error', 'Please log in to proceed with booking.');
            return redirect()->to('/auth/login');
        }

        $type = $this->request->getGet('type'); // flight or hotel
        $id = $this->request->getGet('id');
        $price = $this->request->getGet('price') ?? 5000;

        $data['title'] = 'Secure Checkout';
        $data['booking_type'] = $type;
        $data['item_id'] = $id;
        $data['base_price'] = $price;
        $data['taxes'] = $price * 0.18; // 18% GST dummy
        $data['total'] = $price + $data['taxes'];

        return view('checkout/index', $data);
    }

    public function process()
    {
        $db = \Config\Database::connect();
        
        $type = $this->request->getPost('booking_type') ?? 'flight';
        $itemId = $this->request->getPost('item_id') ?? 1;
        $total = $this->request->getPost('total') ?? 5000;

        try {
            $db->table('bookings')->insert([
                'user_id' => session()->get('id'),
                'booking_type' => $type,
                'item_id' => $itemId,
                'status' => 'confirmed',
                'total_amount' => $total
            ]);
            session()->setFlashdata('success', 'Payment successful! Your booking is confirmed dynamically.');
        } catch (\Exception $e) {
            session()->setFlashdata('success', 'Payment successful! (Database offline, mock UI confirmed).');
        }

        return redirect()->to('/dashboard');
    }
}
