<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Booking extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct() 
	{
        error_reporting(0);
        parent::__construct();

       
    }
	public function index()
	{
		$sports = $this->db->get('sports')->result();
        $default_sport = $sports ? $sports[0]->id : 0;

        $pitches = [];
        if ($default_sport) {
            $pitches = $this->db->get_where('pitches', ['sport_id' => $default_sport, 'is_active' => 1])->result();
        }
        $default_pitch = $pitches ? $pitches[0]->id : 0;

        $data = [
            'sports' => $sports,
            'default_sport' => $default_sport,
            'pitches' => $pitches,
            'default_pitch' => $default_pitch,
            'today' => date('Y-m-d')
        ];
		$data['content'] = 'booking';
		$this->load->view('layout_home', $data);
	}
	public function booking_confirm()
	{
		$data['pitch_id']    = $this->input->get('pitch_id');
	    $data['booking_date']= $this->input->get('date');
	    $data['start_time']  = $this->input->get('start');
	    $data['end_time']    = $this->input->get('end');
	    $data['total_price'] = $this->input->get('price');

	    // fetch pitch & sport for display
	    $data['pitch'] = $this->db->get_where("pitches", ["id"=>$data['pitch_id']])->row();
	     $user_id = $this->session->userdata('user_id');
	     $customer = null;

	     if ($user_id) {
	        $customer = $this->db->where('c_id', $user_id)->get('customer')->row();
	     }

	    $data['customer'] = $customer;
		$data['content'] = 'booking_confirm';
		$this->load->view('layout_home', $data);
	}
	public function history($user_mobile = null)
	{
	    if ($this->session->userdata('user_id')) {

	    $this->db->select("b.*, p.name as pitch_name, s.name as sport_name, s.image as sport_image, p.id as pitch_id");
	    $this->db->from("bookings b");
	    $this->db->join("pitches p", "p.id = b.pitch_id", "left");
	    $this->db->join("sports s", "s.id = p.sport_id", "left");
	    $this->db->where("b.user_id", $this->session->userdata('user_id'));
	    $this->db->order_by("b.booking_date DESC, b.start_time DESC");
	    $bookings = $this->db->get()->result();

	    $data = [
	        'bookings' => $bookings
	    ];
	    $data['content'] = 'booking_history';
		$this->load->view('layout_home', $data);
		} else{
			redirect('/');
		}
	}
	public function cancel($id)
	{
	    $this->db->where('id', $id)->update('bookings', ['status' => 'cancelled']);
	    redirect('booking/history');
	}
	public function get_pitches($sport_id)
    {
        $pitches = $this->db->get_where('pitches', ['sport_id' => $sport_id, 'is_active' => 1])->result();
        echo json_encode($pitches);
    }

    public function get_slots()
	{
	    // required inputs
	    $pitch_id = $this->input->post('pitch_id');
	    $date     = $this->input->post('date'); // expected yyyy-mm-dd

	    if (! $pitch_id || ! $date) {
	        echo json_encode([]);
	        return;
	    }

	    // Use Asia/Kolkata timezone explicitly
	    $tz = new DateTimeZone('Asia/Kolkata');

	    // Get day of week (0=Sun...6=Sat)
	    $dayOfWeek = date('w', strtotime($date));

	    // Get pitch_hours for that day
	    $hours = $this->db->get_where('pitch_hours', [
	        'pitch_id'    => $pitch_id,
	        'day_of_week' => $dayOfWeek
	    ])->row();

	    if (! $hours || (int)$hours->is_closed === 1) {
	        echo json_encode([]);
	        return;
	    }

	    $slot_step = intval($hours->slot_step_minutes) ?: 30;

	    // Build DateTime objects for open/close on the requested date (Asia/Kolkata)
	    try {
	        $openDt  = new DateTime("{$date} {$hours->open_time}", $tz);
	        $closeDt = new DateTime("{$date} {$hours->close_time}", $tz);
	    } catch (Exception $e) {
	        // fallback: empty result
	        echo json_encode([]);
	        return;
	    }

	    // Current time in same timezone
	    $nowLocal  = new DateTime('now', $tz);
	    $todayLocal = $nowLocal->format('Y-m-d');

	    // Fetch existing bookings for this pitch+date (pending/confirmed)
	    $bookings = $this->db
	        ->select('start_time, end_time')
	        ->from('bookings')
	        ->where('pitch_id', $pitch_id)
	        ->where('booking_date', $date)
	        ->where_in('status', ['pending','confirmed'])
	        ->get()
	        ->result_array();

	    // Convert bookings to DateTime ranges
	    $bookedRanges = [];
	    foreach ($bookings as $b) {
	        // Make sure times exist and parse safely
	        try {
	            $bStart = new DateTime("{$date} {$b['start_time']}", $tz);
	            $bEnd   = new DateTime("{$date} {$b['end_time']}", $tz);
	            $bookedRanges[] = ['start' => $bStart, 'end' => $bEnd];
	        } catch (Exception $e) {
	            // ignore malformed booking rows
	            continue;
	        }
	    }

	    // Iterate slots
	    $slots = [];
	    $slotDt = clone $openDt;
	    $intervalSpec = 'PT' . $slot_step . 'M';
	    $slotInterval = new DateInterval($intervalSpec);

	    while ($slotDt < $closeDt) {
	        $slotEndDt = (clone $slotDt)->add($slotInterval);

	        // if slot end goes beyond close time, stop
	        if ($slotEndDt > $closeDt) break;

	        // If booking date is today -> skip slots which have already started or are ongoing
	        if ($date === $todayLocal && $slotDt <= $nowLocal) {
	            $slotDt->add($slotInterval);
	            continue;
	        }

	        // Check overlap with existing bookings
	        $isBooked = false;
	        foreach ($bookedRanges as $br) {
	            // overlap if slotStart < bookedEnd AND slotEnd > bookedStart
	            if ($slotDt < $br['end'] && $slotEndDt > $br['start']) {
	                $isBooked = true;
	                break;
	            }
	        }

	        $slots[] = [
	            'start'     => $slotDt->format('H:i:s'),            // for DB/save
	            'end'       => $slotEndDt->format('H:i:s'),         // for DB/save
	            'display'   => $slotDt->format('h:i A') . ' - ' . $slotEndDt->format('h:i A'),
	            'is_booked' => $isBooked
	        ];

	        $slotDt->add($slotInterval);
	    }

	    echo json_encode($slots);
	}


    public function get_price()
    {
        $pitch_id = $this->input->post('pitch_id');
        $date     = $this->input->post('date');
        $start    = $this->input->post('start_time');
        $end      = $this->input->post('end_time');

        $dayOfWeek = date('w', strtotime($date));
        $day_type = in_array($dayOfWeek, [0,6]) ? 'weekend' : 'weekday';

        $this->db->where('pitch_id', $pitch_id);
        $this->db->where('day_type', $day_type);
        $this->db->where("'$start' >= time_start AND '$end' <= time_end");
        $this->db->where("'$date' >= effective_from AND '$date' <= effective_to");
        $this->db->order_by('priority', 'DESC');
        $rate = $this->db->get('rate_cards')->row();

        $price = $rate ? $rate->price : 0;
        echo json_encode(['price' => $price]);
    }

    public function confirm()
    {
        $data = [
            'pitch_id'      => $this->input->post('pitch_id'),
            'user_id'     => '1',
            'booking_date'  => $this->input->post('booking_date'),
            'start_time'    => $this->input->post('start_time'),
            'end_time'      => $this->input->post('end_time'),
            'total_price'   => $this->input->post('total_price'),
            'status'        => 'confirmed'
        ];

        $this->db->insert('bookings', $data);
        echo json_encode(['status' => 'success', 'message' => 'Booking Confirmed!']);
    }
    public function save_booking()
	{
	    $post = $this->input->post();

	    // Check customer
	    $customer = $this->db->where('email', $post['email'])
	                         ->or_where('mobile', $post['phone'])
	                         ->get('customer')->row();

	    if ($customer) {
	        // Update existing
	        $this->db->where('c_id', $customer->c_id)->update('customer', [
	            'name'    => $post['name'],
	            'email'   => $post['email'],
	            'mobile'  => $post['phone'],
	            'address' => $post['address'],
	        ]);
	        $user_id = $customer->c_id;
	    } else {
	        // Generate random password
	        $password = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 8);
	        $user_id = $this->db->insert_id();

	        $this->db->insert('customer', [
	            'name'    => $post['name'],
	            'email'   => $post['email'],
	            'mobile'  => $post['phone'],
	            'address' => $post['address'],
	            'pass'    => base64_encode($password),
	        ]);

	        $user_id = $this->db->insert_id();
	    }

	    $this->session->set_userdata('user_id', $user_id);  
        $this->session->set_userdata('customer', $user_id);          
        $this->session->set_userdata('name', $post['name']);
        $this->session->set_userdata('email', $post['email']);
        $this->session->set_userdata('mobile', $post['phone']);
        $this->session->set_userdata('address', $post['address']);
        $this->session->set_userdata('login_session', true);


	    // Save booking
	    $this->db->insert('bookings', [
	        'pitch_id'     => $post['pitch_id'],
	        'user_id'      => $user_id,
	        'booking_date' => $post['booking_date'],
	        'start_time'   => $post['start_time'],
	        'end_time'     => $post['end_time'],
	        'total_price'  => $post['total_price'],
	        'pay_type'     => $post['payment'],
	        'txn_id'       => '', // update after payment gateway success
	        'status'       => 'pending',
	    ]);

	    $booking_id = $this->db->insert_id();
	    $booking_no='TTA0'.date('ymd').$booking_id;

	    $this->db->where('id', $booking_id)->update('bookings', [
	            'booking_no'    => $booking_no,
	        ]);
	    // Redirect to payment or success page
	    if ($post['payment'] == 'online') {
	        redirect('payment/initiate/' . $booking_id);
	    } else {
	        redirect('booking/success/' . $booking_id);
	    }
	}

		
	public function success($booking_id){
		$order_upd = "UPDATE `bookings` SET `status` = 'confirmed' WHERE `id` = '".$booking_id."'";
    	$this->db->query($order_upd); 
    	redirect('booking/thankyou/' . md5($booking_id));
	}
	public function thankyou($booking_id){
		$data['booking_data'] = $this->db->select('*')->where('md5(id)', $booking_id)->get('bookings')->result_array();
		
		$data['content'] = 'thankyou';
        $this->load->view('layout_home', $data); 
	}

}
