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

/**
 * Pickup requests (Firestore collection: Pickup).
 * Pending: assign a driver (driverId, driverName, driverNumber, driverImage) and approve, or reject.
 */
class Aoust_pickup extends CI_Controller
{
	const COLLECTION = 'Pickup';

	public function __construct()
	{
		parent::__construct();
		$this->load->helper(array('url', 'form'));
		$this->load->library('session');
		$this->load->database();

		if (!isset($this->session->userdata['session_data'])) {
			redirect(base_url('login'));
			return;
		}
	}

	public function index()
	{
		$data['page_title'] = 'AOUST — Pickup Requests';
		$data['status_filter'] = strtolower(trim((string) $this->input->get('status'))) ?: 'all';

		$rows = $this->common->readdatafromcollectionwhereclause(self::COLLECTION);
		$list = array();
		if (!empty($rows)) {
			foreach ($rows as $id => $r) {
				if (is_array($r)) {
					$r['id'] = $id;
					$list[] = $r;
				}
			}
		}
		usort($list, function ($a, $b) {
			$ta = isset($a['createdAt']) ? (int) $a['createdAt'] : 0;
			$tb = isset($b['createdAt']) ? (int) $b['createdAt'] : 0;
			if ($ta !== $tb) {
				return $tb <=> $ta;
			}
			$pa = isset($a['pickupTimestamp']) ? (int) $a['pickupTimestamp'] : 0;
			$pb = isset($b['pickupTimestamp']) ? (int) $b['pickupTimestamp'] : 0;
			return $pb <=> $pa;
		});

		$filter = $data['status_filter'];
		if ($filter !== 'all' && in_array($filter, array('pending', 'approved', 'rejected'), true)) {
			$filtered = array();
			foreach ($list as $row) {
				if ($this->_norm_status($row) === $filter) {
					$filtered[] = $row;
				}
			}
			$list = $filtered;
		}

		$data['pickups'] = $list;
		$data['drivers'] = $this->_load_drivers_for_select();
		$this->template->template_render('admin/pickup/index', $data);
	}

	public function approve()
	{
		$pickupId = trim((string) $this->input->post('pickup_id'));
		$driverId = trim((string) $this->input->post('driver_id'));
		if ($pickupId === '' || $driverId === '') {
			$this->session->set_flashdata('warningmessage', 'Pickup and driver are required.');
			redirect(base_url('aoust_pickup'));
			return;
		}

		$pickup = $this->common->readdatadocument(self::COLLECTION, $pickupId);
		if (empty($pickup) || !is_array($pickup)) {
			$this->session->set_flashdata('warningmessage', 'Pickup not found.');
			redirect(base_url('aoust_pickup'));
			return;
		}
		if (!$this->_is_pending_row($pickup)) {
			$this->session->set_flashdata('warningmessage', 'Only pending pickups can be approved with a driver.');
			redirect(base_url('aoust_pickup'));
			return;
		}

		$driver = $this->common->readdatadocument('Drivers', $driverId);
		if (empty($driver) || !is_array($driver)) {
			$this->session->set_flashdata('warningmessage', 'Driver not found.');
			redirect(base_url('aoust_pickup'));
			return;
		}

		$name = isset($driver['name']) ? trim((string) $driver['name']) : '';
		$phone = isset($driver['phone']) ? trim((string) $driver['phone']) : '';
		$image = isset($driver['image']) ? trim((string) $driver['image']) : '';

		$update = array(
			'driverId' => $driverId,
			'driverName' => $name,
			'driverNumber' => $phone,
			'driverImage' => ($image !== '') ? $image : null,
			'status' => 'approved',
			'updatedAt' => round(microtime(true) * 1000),
		);

		try {
			$this->common->updatedatamodel(self::COLLECTION, $pickupId, $update);
			$this->session->set_flashdata('successmessage', 'Pickup approved and driver assigned.');
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Failed to update pickup.');
		}
		redirect(base_url('aoust_pickup'));
	}

	public function reject()
	{
		$pickupId = trim((string) $this->input->post('pickup_id'));
		if ($pickupId === '') {
			$this->session->set_flashdata('warningmessage', 'Pickup is required.');
			redirect(base_url('aoust_pickup'));
			return;
		}

		$pickup = $this->common->readdatadocument(self::COLLECTION, $pickupId);
		if (empty($pickup) || !is_array($pickup)) {
			$this->session->set_flashdata('warningmessage', 'Pickup not found.');
			redirect(base_url('aoust_pickup'));
			return;
		}
		if (!$this->_is_pending_row($pickup)) {
			$this->session->set_flashdata('warningmessage', 'Only pending pickups can be rejected.');
			redirect(base_url('aoust_pickup'));
			return;
		}

		$update = array(
			'status' => 'rejected',
			'driverId' => null,
			'driverName' => null,
			'driverNumber' => null,
			'driverImage' => null,
			'updatedAt' => round(microtime(true) * 1000),
		);

		try {
			$this->common->updatedatamodel(self::COLLECTION, $pickupId, $update);
			$this->session->set_flashdata('successmessage', 'Pickup rejected.');
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Failed to update pickup.');
		}
		redirect(base_url('aoust_pickup'));
	}

	private function _load_drivers_for_select()
	{
		$rows = $this->common->readdatafromcollectionwhereclause('Drivers');
		$list = array();
		if (!empty($rows)) {
			foreach ($rows as $id => $r) {
				if (is_array($r)) {
					$r['id'] = $id;
					$list[] = $r;
				}
			}
		}
		usort($list, function ($a, $b) {
			$na = isset($a['name']) ? strtolower((string) $a['name']) : '';
			$nb = isset($b['name']) ? strtolower((string) $b['name']) : '';
			return strcmp($na, $nb);
		});
		return $list;
	}

	private function _norm_status($row)
	{
		$s = isset($row['status']) ? strtolower(trim((string) $row['status'])) : '';
		if ($s === 'pending' || $s === 'approved' || $s === 'rejected') {
			return $s;
		}
		return $s;
	}

	private function _is_pending_row($row)
	{
		return $this->_norm_status($row) === 'pending';
	}
}
