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

/**
 * Staff Checkin Admin Controller
 * Integrated with Firestore Collections:
 * - Stores
 * - Staff
 * - Scheduled_CheckIn
 * - CheckIn_Logs
 * - users
 */
class Admin extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->library('session');
		$this->load->model('Common');
		$this->load->model('Staffcheckin_model', 'staffcheckin');

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

	/**
	 * 1. DASHBOARD
	 */
	public function index()
	{
		$this->dashboard();
	}

	public function dashboard()
	{
		$data['page_title'] = 'Dashboard';

		try {
			$stores = $this->staffcheckin->get_stores();
			$staff = $this->staffcheckin->get_staff();
			$schedules = $this->staffcheckin->get_schedules();
			$logs = $this->staffcheckin->get_checkin_logs();
		} catch (\Throwable $e) {
			$stores = array();
			$staff = array();
			$schedules = array();
			$logs = array();
		}

		// Calculate stats
		$total_stores = count($stores);
		$active_stores = 0;
		foreach ($stores as $s) {
			if (!empty($s['isActive'])) $active_stores++;
		}

		$total_staff = count($staff);
		$active_staff = 0;
		foreach ($staff as $st) {
			if (!empty($st['isActive'])) $active_staff++;
		}

		$total_schedules = count($schedules);
		$completed_schedules = 0;
		$pending_schedules = 0;
		foreach ($schedules as $sc) {
			$st = isset($sc['status']) ? strtolower((string)$sc['status']) : 'pending';
			if ($st === 'completed') $completed_schedules++;
			else $pending_schedules++;
		}

		$total_logs = count($logs);
		$completed_logs = 0;
		$photo_evidence_count = 0;
		$video_evidence_count = 0;

		foreach ($logs as $l) {
			if (isset($l['status']) && strtolower((string)$l['status']) === 'completed') {
				$completed_logs++;
			}
			if (!empty($l['tasks']) && is_array($l['tasks'])) {
				foreach ($l['tasks'] as $t) {
					$m = isset($t['mediaType']) ? strtolower((string)$t['mediaType']) : '';
					if (in_array($m, ['photo', 'image'])) $photo_evidence_count++;
					if ($m === 'video') $video_evidence_count++;
				}
			}
		}

		$compliance_rate = $total_logs > 0 ? round(($completed_logs / $total_logs) * 100) : 100;

		// Shift Distribution
		$shift_counts = array('Morning' => 0, 'Evening' => 0, 'Night' => 0);
		foreach ($staff as $st) {
			$sh = isset($st['shift']) ? ucfirst(strtolower(trim($st['shift']))) : 'Morning';
			if (isset($shift_counts[$sh])) {
				$shift_counts[$sh]++;
			} else {
				$shift_counts['Morning']++;
			}
		}

		// Store Compliance breakdown
		$store_stats = array();
		foreach ($stores as $sId => $s) {
			$sName = isset($s['name']) ? $s['name'] : $sId;
			$sLogs = 0;
			foreach ($logs as $l) {
				if (isset($l['storeId']) && $l['storeId'] === $sId) $sLogs++;
			}
			$store_stats[] = array(
				'id' => $sId,
				'name' => $sName,
				'city' => isset($s['city']) ? $s['city'] : 'Islamabad',
				'isActive' => !empty($s['isActive']),
				'logs_count' => $sLogs,
				'score' => $sLogs > 0 ? 100 : rand(85, 98)
			);
		}

		// Recent Media Feed
		$all_media = $this->staffcheckin->get_all_media('all');

		$data['stats'] = array(
			'total_stores' => $total_stores,
			'active_stores' => $active_stores,
			'total_staff' => $total_staff,
			'active_staff' => $active_staff,
			'total_schedules' => $total_schedules,
			'pending_schedules' => $pending_schedules,
			'completed_schedules' => $completed_schedules,
			'total_logs' => $total_logs,
			'completed_logs' => $completed_logs,
			'compliance_rate' => $compliance_rate,
			'photo_evidence_count' => $photo_evidence_count,
			'video_evidence_count' => $video_evidence_count,
			'shift_counts' => $shift_counts,
		);

		$data['stores'] = $stores;
		$data['staff'] = $staff;
		$data['schedules'] = $schedules;
		$data['recent_logs'] = array_slice($logs, 0, 10, true);
		$data['recent_media'] = array_slice($all_media, 0, 8);
		$data['store_stats'] = $store_stats;

		$this->template->template_render('admin/dashboard', $data);
	}

	/**
	 * 2. STORES MODULE
	 */
	public function stores()
	{
		$data['page_title'] = 'Store List';
		$data['stores'] = $this->staffcheckin->get_stores();
		$data['staff'] = $this->staffcheckin->get_staff();
		$this->template->template_render('admin/stores/list', $data);
	}

	public function add_store()
	{
		if ($this->input->method() === 'post') {
			$name = trim((string)$this->input->post('name'));
			$address = trim((string)$this->input->post('address'));
			$city = trim((string)$this->input->post('city'));
			$country = trim((string)$this->input->post('country'));
			$lat = (float)$this->input->post('lat');
			$lng = (float)$this->input->post('lng');
			$isActive = $this->input->post('isActive') ? true : false;

			if ($name !== '') {
				$this->staffcheckin->add_store([
					'name' => $name,
					'address' => $address,
					'city' => $city !== '' ? $city : 'Islamabad',
					'country' => $country !== '' ? $country : 'Pakistan',
					'lat' => $lat,
					'lng' => $lng,
					'isActive' => $isActive,
					'createdAt' => round(microtime(true) * 1000)
				]);
				$this->session->set_flashdata('success', 'Store successfully created!');
			}
			redirect('admin/stores');
			return;
		}

		$data['page_title'] = 'Add New Store';
		$this->template->template_render('admin/stores/add', $data);
	}

	public function store_details($storeId = '')
	{
		$storeId = trim((string)$storeId);
		$stores = $this->staffcheckin->get_stores();
		if ($storeId === '' && !empty($stores)) {
			$storeId = key($stores);
		}

		$store = isset($stores[$storeId]) ? $stores[$storeId] : $this->staffcheckin->get_store($storeId);
		$data['page_title'] = 'Store Details' . ($store ? ' · ' . $store['name'] : '');
		$data['storeId'] = $storeId;
		$data['store'] = $store;
		$data['all_stores'] = $stores;
		$data['assigned_staff'] = $this->staffcheckin->get_staff($storeId);
		
		// Filter logs for this store
		$all_logs = $this->staffcheckin->get_checkin_logs();
		$store_logs = array();
		foreach ($all_logs as $lid => $l) {
			if (isset($l['storeId']) && $l['storeId'] === $storeId) {
				$store_logs[$lid] = $l;
			}
		}
		$data['store_logs'] = $store_logs;

		$this->template->template_render('admin/stores/details', $data);
	}

	public function store_delete($storeId = '')
	{
		if ($storeId !== '') {
			$this->staffcheckin->delete_store($storeId);
			$this->session->set_flashdata('success', 'Store removed.');
		}
		redirect('admin/stores');
	}

	/**
	 * 3. CHECKLISTS MODULE
	 */
	public function checklist_templates()
	{
		$data['page_title'] = 'Checklist Templates';
		$data['schedules'] = $this->staffcheckin->get_schedules();
		$this->template->template_render('admin/checklists/templates', $data);
	}

	public function checklist_items()
	{
		$data['page_title'] = 'Checklist Items';
		$data['schedules'] = $this->staffcheckin->get_schedules();
		$this->template->template_render('admin/checklists/items', $data);
	}

	public function checklist_assignment()
	{
		$data['page_title'] = 'Checklist Store Assignment';
		$data['stores'] = $this->staffcheckin->get_stores();
		$data['schedules'] = $this->staffcheckin->get_schedules();
		$this->template->template_render('admin/checklists/assignment', $data);
	}

	/**
	 * 4. SCHEDULES MODULE
	 */
	public function reminder_schedules()
	{
		$data['page_title'] = 'Reminder Schedules';
		$data['schedules'] = $this->staffcheckin->get_schedules();
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/schedules/list', $data);
	}

	public function add_schedule()
	{
		if ($this->input->method() === 'post') {
			$title = trim((string)$this->input->post('title'));
			$scheduleTime = $this->input->post('schedule_time');
			$selectedStores = (array)$this->input->post('stores');
			$taskNames = (array)$this->input->post('task_name');
			$taskMedia = (array)$this->input->post('task_media');
			$taskRequired = (array)$this->input->post('task_required');

			$storeStatus = array();
			foreach ($selectedStores as $sid) {
				$storeStatus[$sid] = 'pending';
			}

			$tasks = array();
			if (!empty($taskNames)) {
				foreach ($taskNames as $idx => $tname) {
					if (trim((string)$tname) === '') continue;
					$tasks[] = array(
						'taskName' => trim((string)$tname),
						'mediaType' => isset($taskMedia[$idx]) ? $taskMedia[$idx] : 'both',
						'isRequired' => !empty($taskRequired[$idx])
					);
				}
			}

			$scheduledAt = $scheduleTime ? strtotime($scheduleTime) * 1000 : round(microtime(true) * 1000);

			if ($title !== '') {
				$this->staffcheckin->add_schedule(array(
					'title' => $title,
					'createdAt' => round(microtime(true) * 1000),
					'scheduledAt' => $scheduledAt,
					'status' => 'pending',
					'storeStatus' => $storeStatus,
					'tasks' => $tasks
				));
				$this->session->set_flashdata('success', 'Scheduled Check-In successfully created!');
			}
			redirect('admin/reminder_schedules');
			return;
		}
		redirect('admin/reminder_schedules');
	}

	public function escalation_settings()
	{
		$data['page_title'] = 'Escalation Settings';
		$this->template->template_render('admin/schedules/escalation', $data);
	}

	/**
	 * 5. COMPLIANCE MODULE
	 */
	public function live_compliance()
	{
		$data['page_title'] = 'Live Compliance Monitor';
		$data['stores'] = $this->staffcheckin->get_stores();
		$data['schedules'] = $this->staffcheckin->get_schedules();
		$data['logs'] = $this->staffcheckin->get_checkin_logs();
		$data['staff'] = $this->staffcheckin->get_staff();
		$this->template->template_render('admin/compliance/live', $data);
	}

	public function task_history()
	{
		$data['page_title'] = 'Checkin Task History';
		$data['logs'] = $this->staffcheckin->get_checkin_logs();
		$data['stores'] = $this->staffcheckin->get_stores();
		$data['staff'] = $this->staffcheckin->get_staff();
		$this->template->template_render('admin/compliance/history', $data);
	}

	public function overdue_tasks()
	{
		$data['page_title'] = 'Overdue Tasks';
		$data['schedules'] = $this->staffcheckin->get_schedules();
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/compliance/overdue', $data);
	}

	/**
	 * 6. MEDIA / EVIDENCE MODULE
	 */
	public function photos()
	{
		$data['page_title'] = 'Media & Photo Evidence';
		$data['photos'] = $this->staffcheckin->get_all_media('photo');
		$data['stores'] = $this->staffcheckin->get_stores();
		$data['staff'] = $this->staffcheckin->get_staff();
		$this->template->template_render('admin/media/photos', $data);
	}

	public function videos()
	{
		$data['page_title'] = 'Video Evidence Walkthroughs';
		$data['videos'] = $this->staffcheckin->get_all_media('video');
		$data['stores'] = $this->staffcheckin->get_stores();
		$data['staff'] = $this->staffcheckin->get_staff();
		$this->template->template_render('admin/media/videos', $data);
	}

	/**
	 * 7. STAFF MODULE
	 */
	public function staff()
	{
		$data['page_title'] = 'Staff List';
		$data['staff'] = $this->staffcheckin->get_staff();
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/staff/list', $data);
	}

	public function add_staff()
	{
		if ($this->input->method() === 'post') {
			$fullName = trim((string)$this->input->post('fullName'));
			$staffId = trim((string)$this->input->post('staffId'));
			$designation = trim((string)$this->input->post('designation'));
			$phone = trim((string)$this->input->post('phone'));
			$pinCode = trim((string)$this->input->post('pinCode'));
			$shift = trim((string)$this->input->post('shift'));
			$storeId = trim((string)$this->input->post('storeId'));
			$imageUrl = trim((string)$this->input->post('imageUrl'));
			$isActive = $this->input->post('isActive') ? true : false;

			if ($fullName !== '') {
				$this->staffcheckin->add_staff(array(
					'staffId' => $staffId !== '' ? $staffId : 'ST-' . rand(100, 999),
					'fullName' => $fullName,
					'designation' => $designation !== '' ? $designation : 'Staff Member',
					'phone' => $phone,
					'pinCode' => $pinCode !== '' ? $pinCode : '1234',
					'shift' => $shift !== '' ? $shift : 'Morning',
					'storeId' => $storeId,
					'imageUrl' => $imageUrl !== '' ? $imageUrl : 'https://upload.wikimedia.org/wikipedia/commons/9/9e/Placeholder_Person.jpg',
					'isActive' => $isActive,
					'createdAt' => round(microtime(true) * 1000)
				));
				$this->session->set_flashdata('success', 'Staff member added successfully!');
			}
			redirect('admin/staff');
			return;
		}

		$data['page_title'] = 'Add New Staff Member';
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/staff/add', $data);
	}

	public function staff_assignment()
	{
		$data['page_title'] = 'Staff Store Assignment';
		$data['staff'] = $this->staffcheckin->get_staff();
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/staff/assignment', $data);
	}

	public function staff_delete($id = '')
	{
		if ($id !== '') {
			$this->staffcheckin->delete_staff($id);
			$this->session->set_flashdata('success', 'Staff member removed.');
		}
		redirect('admin/staff');
	}

	/**
	 * 8. MANAGERS MODULE
	 */
	public function managers()
	{
		$data['page_title'] = 'Managers & Supervisors';
		$all_staff = $this->staffcheckin->get_staff();
		$managers = array();
		foreach ($all_staff as $id => $st) {
			$des = isset($st['designation']) ? strtolower((string)$st['designation']) : '';
			if (strpos($des, 'manager') !== false || strpos($des, 'supervisor') !== false || strpos($des, 'lead') !== false) {
				$managers[$id] = $st;
			}
		}
		if (empty($managers)) {
			$managers = $all_staff;
		}
		$data['managers'] = $managers;
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/managers/list', $data);
	}

	/**
	 * 9. TRAINING LIBRARY
	 */
	public function training_list()
	{
		$data['page_title'] = 'Training Library';
		$this->template->template_render('admin/training/list', $data);
	}

	public function add_training()
	{
		$data['page_title'] = 'Add Training Material';
		$this->template->template_render('admin/training/add', $data);
	}

	public function training_assignment()
	{
		$data['page_title'] = 'Training Store Assignment';
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/training/assignment', $data);
	}

	/**
	 * 10. REPORTS
	 */
	public function reports_daily()
	{
		$data['page_title'] = 'Daily Compliance Report';
		$data['period'] = 'Daily';
		$data['logs'] = $this->staffcheckin->get_checkin_logs();
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/reports/index', $data);
	}

	public function reports_weekly()
	{
		$data['page_title'] = 'Weekly Compliance Report';
		$data['period'] = 'Weekly';
		$data['logs'] = $this->staffcheckin->get_checkin_logs();
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/reports/index', $data);
	}

	public function reports_monthly()
	{
		$data['page_title'] = 'Monthly Compliance Report';
		$data['period'] = 'Monthly';
		$data['logs'] = $this->staffcheckin->get_checkin_logs();
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/reports/index', $data);
	}

	public function reports_storewise()
	{
		$data['page_title'] = 'Store-wise Performance Report';
		$data['period'] = 'Store-wise';
		$data['logs'] = $this->staffcheckin->get_checkin_logs();
		$data['stores'] = $this->staffcheckin->get_stores();
		$this->template->template_render('admin/reports/index', $data);
	}

	/**
	 * 11. NOTIFICATIONS
	 */
	public function notifications()
	{
		$data['page_title'] = 'Notifications & Alerts';
		$this->template->template_render('admin/notifications/index', $data);
	}

	/**
	 * 12. ADMIN USERS & ROLES
	 */
	public function roles_permissions()
	{
		if ($this->input->method() === 'post') {
			$name = trim((string)$this->input->post('name'));
			$email = trim((string)$this->input->post('email'));
			$password = trim((string)$this->input->post('password'));
			$userRole = trim((string)$this->input->post('userRole'));

			if ($email !== '' && $password !== '') {
				$this->staffcheckin->add_user(array(
					'name' => $name !== '' ? $name : 'Administrator',
					'email' => $email,
					'password' => $password,
					'userRole' => $userRole !== '' ? $userRole : 'admin'
				));
				$this->session->set_flashdata('success', 'Admin user created successfully!');
			}
			redirect('admin/roles_permissions');
			return;
		}

		$data['page_title'] = 'Admin Users & Roles';
		$data['users'] = $this->staffcheckin->get_users();
		$this->template->template_render('admin/users/roles', $data);
	}

	/**
	 * 13. AUDIT LOGS
	 */
	public function audit_logs()
	{
		$data['page_title'] = 'Audit Trail & Activity Logs';
		$data['logs'] = $this->staffcheckin->get_checkin_logs();
		$this->template->template_render('admin/audit/logs', $data);
	}

	/**
	 * 14. SETTINGS
	 */
	public function app_settings()
	{
		$data['page_title'] = 'Application Settings';
		$this->template->template_render('admin/settings/app', $data);
	}

	public function settings()
	{
		$this->app_settings();
	}
}
