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

class Pitches extends CI_Controller {

	function __construct() 
	{
        error_reporting(0);
        parent::__construct();
        $this->load->model('CommonModel');
        $this->load->helper('Security');
        $this->load->library('form_validation');

       
    }

	public function index()
	{ 
		if(isAdmin())
		{ 
			$data['recordSet']=$this->db->select('p.id,p.name,p.slot_step_minutes,p.max_advance_days,p.is_active,s.name as sport_name')->from('pitches as p')->join('sports as s', 'p.sport_id = s.id', 'LEFT')->order_by('id','desc')->get()->result_array();
			$data['content'] = 'Pitches/Listing';
			$this->load->view('layout_home', $data);
		}
	}

	public function add()
	{
		if(isAdmin())
		{
			//$data['recordSet']=$this->db->get('vehicle_type')->result_array();
			$data['category']=$this->db->get('sports')->result_array();
			$data['content'] = 'Pitches/Add';
			$this->load->view('layout_home', $data);
		}
	}
	public function rate_card_add($id)
	{
		if(isAdmin())
		{
			//$data['recordSet']=$this->db->get('vehicle_type')->result_array();
			$data['pitch']=$this->db->where('id',$id)->get('pitches')->row();
			$data['content'] = 'Pitches/RateAdd';
			$this->load->view('layout_home', $data);
		}
	}
	public function rate_cards($pitch_id)
	{
		if(isAdmin())
		{
			$pitch = $this->db->where('id',$pitch_id)->get('pitches')->row();
	        if (!$pitch) show_404();

	        $data['pitch'] = $pitch;
	        $data['rates'] = $this->db->where('pitch_id',$pitch_id)->order_by('priority','asc')->get('rate_cards')->result();
			$data['content'] = 'Pitches/RateListing';
			$this->load->view('layout_home', $data);
		}
	}
	public function edit($d_id)
	{
		if(isAdmin())
		{
			$pitches = $this->db->get_where('pitches', ['id' => $d_id])->row_array();
		    $category = $this->db->get('sports')->result_array();

		    $data = [
		        'pitches' => $pitches,
		        'category' => $category
		    ];
            $data['content']  ="Pitches/Edit";
            $this->load->view('layout_home',$data);
		}
	}
	public function save()
	{
		if(isAdmin())
		{
			$input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);
            
        	$insert_data['sport_id'] = $input_data['sport_id'];
        	$insert_data['name'] = $input_data['name'];
        	$insert_data['slot_step_minutes'] = $input_data['slot_step_minutes'];
        	$insert_data['max_advance_days'] = $input_data['max_advance_days'];
            $this->db->insert('pitches',$insert_data);
	            
            echo 'Success';
        }
		
	}
	public function rate_card_save()
	{
		if(isAdmin())
		{
        	$ins = [
                    'pitch_id' => $this->input->post('pitch_id'),
                    'day_type' => $this->input->post('day_type'),
                    'time_start' => $this->input->post('time_start') ?: null,
                    'time_end' => $this->input->post('time_end') ?: null,
                    'slot_minutes' => (int)$this->input->post('slot_minutes'),
                    'price' => (float)$this->input->post('price'),
                    'effective_from' => $this->input->post('effective_from') ?: null,
                    'effective_to' => $this->input->post('effective_to') ?: null,
                    'priority' => (int)$this->input->post('priority', TRUE)
                ];
                $this->db->insert('rate_cards', $ins);
	            
            echo 'Success';
        }
		
	}

	public function Edit_data()
	{
	    if(isAdmin())
	    {  
        	$input_data = $this->input->post();
            $input_data = $this->security->xss_clean($input_data);

            	$insert_data['sport_id'] = $input_data['sport_id'];
	        	$insert_data['name'] = $input_data['name'];
	        	$insert_data['slot_step_minutes'] = $input_data['slot_step_minutes'];
	        	$insert_data['max_advance_days'] = $input_data['max_advance_days'];
	            $this->db->where('id',$input_data['id']);
	            $this->db->update('pitches',$insert_data);

	            echo 'success';
	    }      
	}
	public function status_change()
	{
	    if(isAdmin())
	    {  
	        	$input_data = $this->input->post();
	            $input_data = $this->security->xss_clean($input_data);
	        	$edit_data['status'] = $input_data['new_status'];
	        	
	            $this->db->where('prd_id',$input_data['id']);
	            $this->db->update('product',$edit_data);
	            echo 'success';
	    }      
	}

	public function Delete()
    {
        if(isAdmin())
        {
        	$input_data = $this->input->post();
        	$this->db->where('d_id', $input_data['id']);
			$this->db->delete('doctor_list');
             // / ---------------------------Insert Audit trail--------------------
            $audit_trail_table='audit_trail';
	        $audit_trail_array=array(
	                                    'user_name'=>$this->session->userdata('admin_name'),
	                                    'action'=>'Action -> "Delete Doctor"',
	                                    'action_time'=>date('Y-m-d H:i:s')
	                                );
        	$this->CommonModel->insert($audit_trail_table,$audit_trail_array);
        }
    }
public function pitch_hours_get($pitch_id) {
    if (!isAdmin()) return;

    $pitch_id = intval($pitch_id);
    $query = $this->db->get_where('pitch_hours', ['pitch_id' => $pitch_id]);
    $hours = $query->result_array();

    // convert to array by day_of_week
    $hours_by_day = [];
    foreach ($hours as $row) {
        $hours_by_day[$row['day_of_week']] = $row;
    }

    $days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

    // slot_step_minutes from any existing row
    $slot_step_minutes_value = '';
    if (!empty($hours)) {
        $slot_step_minutes_value = $hours[0]['slot_step_minutes'];
    }

    echo '
      <div class="form-group">
        <label>Default slot step minutes (applied to each day if left blank)</label>
        <input type="number" name="slot_step_minutes" class="form-control"
               value="'.$slot_step_minutes_value.'">
      </div>

      <table class="table table-bordered">
        <thead>
          <tr>
            <th>Day</th>
            <th>Closed?</th>
            <th>Open</th>
            <th>Close</th>
          </tr>
        </thead>
        <tbody>';

    for ($d = 0; $d <= 6; $d++) {
        $h = isset($hours_by_day[$d]) ? $hours_by_day[$d] : null;
        echo '<tr>';
        echo '<td>'.$days[$d].'</td>';
        echo '<td><input type="checkbox" name="is_closed['.$d.']" value="1" '.($h && $h['is_closed'] ? 'checked' : '').'></td>';
        echo '<td><input type="time" class="form-control" name="open_time['.$d.']" value="'.($h ? $h['open_time'] : '06:00').'"></td>';
        echo '<td><input type="time" class="form-control" name="close_time['.$d.']" value="'.($h ? $h['close_time'] : '23:00').'"></td>';
        echo '</tr>';
    }

    echo '</tbody></table>';
}

public function pitch_hours_save() {
    if (!isAdmin()) return;

    $pitch_id          = intval($this->input->post('pitch_id'));
    $slot_step_minutes = intval($this->input->post('slot_step_minutes'));
    $open_time         = $this->input->post('open_time');
    $close_time        = $this->input->post('close_time');
    $is_closed         = $this->input->post('is_closed');

    if (empty($pitch_id)) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid pitch']);
        return;
    }

    // Loop through days 0–6 (Sun-Sat)
    for ($d = 0; $d <= 6; $d++) {
        $data = [
            'pitch_id'          => $pitch_id,
            'day_of_week'       => $d,
            'open_time'         => isset($open_time[$d]) ? $open_time[$d] : '06:00',
            'close_time'        => isset($close_time[$d]) ? $close_time[$d] : '23:00',
            'slot_step_minutes' => $slot_step_minutes ?: 60, // fallback default 60
            'is_closed'         => isset($is_closed[$d]) ? 1 : 0
        ];

        // Validate open < close
        if (!$data['is_closed'] && strtotime($data['open_time']) >= strtotime($data['close_time'])) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid time range for '.$d]);
            return;
        }

        // check if record exists
        $exists = $this->db->get_where('pitch_hours', [
            'pitch_id' => $pitch_id,
            'day_of_week' => $d
        ])->row_array();

        if ($exists) {
            $this->db->where('id', $exists['id']);
            $this->db->update('pitch_hours', $data);
        } else {
            $this->db->insert('pitch_hours', $data);
        }
    }

    echo json_encode(['status' => 'success', 'message' => 'Hours saved successfully']);
}


}