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

/**
 * Pickup drivers directory (Firestore: Drivers).
 * Simple records: name, phone, image URL — no Firebase Auth linkage.
 */
class Aoust_driver extends CI_Controller
{
	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 Drivers';
		$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) {
			$ta = isset($a['timeStamp']) ? (int) $a['timeStamp'] : 0;
			$tb = isset($b['timeStamp']) ? (int) $b['timeStamp'] : 0;
			return $tb <=> $ta;
		});
		$data['drivers'] = $list;
		$this->template->template_render('admin/driver/index', $data);
	}

	public function create()
	{
		$data['page_title'] = 'AOUST — Add Driver';
		$data['mode'] = 'create';
		$data['driver'] = $this->_empty_driver();
		$this->template->template_render('admin/driver/form', $data);
	}

	public function store()
	{
		$payload = $this->_read_payload_from_post();
		if ($payload['name'] === '' || $payload['phone'] === '') {
			$this->session->set_flashdata('warningmessage', 'Name and phone are required.');
			redirect(base_url('aoust_driver/create'));
			return;
		}

		$docId = 'drv_' . uniqid();
		$payload['timeStamp'] = round(microtime(true) * 1000);
		$payload['createdAt'] = date('c');
		$payload['updatedAt'] = date('c');

		$nameSlug = $this->_slug($payload['name']);
		$payload['image'] = $this->_maybe_upload('image', 'drivers/' . $docId . '/' . $nameSlug . '-photo');

		$ok = $this->common->adddatamodel('Drivers', $docId, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Driver added.');
			redirect(base_url('aoust_driver'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to save driver.');
		redirect(base_url('aoust_driver/create'));
	}

	public function edit($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_driver'));
			return;
		}
		$row = $this->common->readdatadocument('Drivers', $id);
		if (empty($row) || !is_array($row)) {
			$this->session->set_flashdata('warningmessage', 'Driver not found.');
			redirect(base_url('aoust_driver'));
			return;
		}
		$row['id'] = $id;
		$data['page_title'] = 'AOUST — Edit Driver';
		$data['mode'] = 'edit';
		$data['driver'] = array_merge($this->_empty_driver(), $row);
		$this->template->template_render('admin/driver/form', $data);
	}

	public function update($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_driver'));
			return;
		}
		$existing = $this->common->readdatadocument('Drivers', $id);
		if (empty($existing) || !is_array($existing)) {
			$this->session->set_flashdata('warningmessage', 'Driver not found.');
			redirect(base_url('aoust_driver'));
			return;
		}

		$payload = $this->_read_payload_from_post();
		if ($payload['name'] === '' || $payload['phone'] === '') {
			$this->session->set_flashdata('warningmessage', 'Name and phone are required.');
			redirect(base_url('aoust_driver/edit/' . rawurlencode($id)));
			return;
		}

		$payload['updatedAt'] = date('c');
		$nameSlug = $this->_slug($payload['name']);
		$newImage = $this->_maybe_upload('image', 'drivers/' . $id . '/' . $nameSlug . '-photo');
		$payload['image'] = ($newImage !== '') ? $newImage : (isset($existing['image']) ? (string) $existing['image'] : '');

		$ok = $this->common->updatedatamodel('Drivers', $id, $payload);
		if ($ok) {
			$this->session->set_flashdata('successmessage', 'Driver updated.');
			redirect(base_url('aoust_driver'));
			return;
		}
		$this->session->set_flashdata('warningmessage', 'Failed to update driver.');
		redirect(base_url('aoust_driver/edit/' . rawurlencode($id)));
	}

	public function delete($id = '')
	{
		$id = trim((string) $id);
		if ($id === '') {
			redirect(base_url('aoust_driver'));
			return;
		}
		$this->common->deletedatamodel('Drivers', $id);
		$this->session->set_flashdata('successmessage', 'Driver deleted.');
		redirect(base_url('aoust_driver'));
	}

	private function _empty_driver()
	{
		return array(
			'id' => '',
			'name' => '',
			'phone' => '',
			'image' => '',
		);
	}

	private function _read_payload_from_post()
	{
		return array(
			'name' => trim((string) $this->input->post('name')),
			'phone' => trim((string) $this->input->post('phone')),
			'image' => '',
		);
	}

	private function _slug($s)
	{
		$s = strtolower(trim((string) $s));
		$s = preg_replace('/[^a-z0-9]+/', '-', $s);
		$s = trim($s, '-');
		return $s ?: 'driver';
	}

	private function _maybe_upload($field, $pathPrefix)
	{
		if (!isset($_FILES[$field]) || !is_array($_FILES[$field])) return '';
		if (!isset($_FILES[$field]['tmp_name']) || $_FILES[$field]['tmp_name'] === '') return '';
		if (!is_uploaded_file($_FILES[$field]['tmp_name'])) return '';

		$tmp = $_FILES[$field]['tmp_name'];
		$orig = isset($_FILES[$field]['name']) ? (string) $_FILES[$field]['name'] : '';
		$ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
		if ($ext === '') $ext = 'bin';
		$objectName = $pathPrefix . '-' . date('YmdHis') . '.' . $ext;

		try {
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$bucket = $storage->getBucket();
			$bucket->upload(
				fopen($tmp, 'r'),
				array(
					'name' => $objectName,
					'predefinedAcl' => 'publicRead',
				)
			);
			return sprintf('https://storage.googleapis.com/%s/%s', $bucket->name(), $objectName);
		} catch (Exception $e) {
			return '';
		}
	}
}
