<?php

/**
 * Result Management System for Institutions
 *
 * Copyright (C) 2025 ASTGD
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
declare(strict_types=1);

/**
 * This file is part of the Result Management System for Institutions plugin.
 *
 * It ensures that the file is being accessed through WordPress by checking if the ABSPATH constant is defined.
 * If ABSPATH is not defined, the script will exit to prevent unauthorized access.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Dashboard
 *
 * Handles the display and functionality of the plugin dashboard
 */
class ASTGDRMSYS_Dashboard {
	/**
	 * @var wpdb WordPress database object
	 */
	private $wpdb;

	/**
	 * @var string Database table prefix
	 */
	private $prefix;

	/**
	 * @var array School information
	 */
	private $schoolInfo = array();

	/**
	 * @var array Classes information
	 */
	private $classes = array();

	/**
	 * Dashboard constructor.
	 */
	public function __construct() {
		global $wpdb;
		$this->wpdb   = $wpdb;
		$this->prefix = $wpdb->prefix;

		$this->fetchData();
	}

	/**
	 * Fetch all necessary data for the dashboard
	 */
	private function fetchData() {
		$this->fetchSchoolInfo();
		$this->fetchClasses();
        }

	/**
	 * Fetch school information
	 */
	private function fetchSchoolInfo() {
		$sanitized_school_table = esc_sql( $this->prefix . 'astgdrmsys_school_info' );
		$sql_school             = "SELECT * FROM `$sanitized_school_table` LIMIT 1";
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery
		$this->schoolInfo = $this->wpdb->get_row( $sql_school, ARRAY_A );
	}

	/**
	 * Fetch classes information
	 */
	private function fetchClasses() {
		$sanitized_class_table = esc_sql( $this->prefix . 'astgdrmsys_class' );
		$sql_classes           = "SELECT * FROM `$sanitized_class_table`";
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery
		$this->classes = $this->wpdb->get_results( $sql_classes, ARRAY_A );
	}

	/**
	 * Get the count of students for a specific class
	 *
	 * @param int $classId The class ID
	 * @return int Number of students
	 */
	private function getStudentCount( $classId, $wpdb ) {
		$sanitized_result_table = esc_sql( $this->prefix . 'astgdrmsys_student_result' );
		$cache_key              = 'student_count_class_' . $classId;
		$studentCount           = wp_cache_get( $cache_key, 'rms' );

		if ( $studentCount === false ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
			$studentCount = $wpdb->get_var(
				$wpdb->prepare(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
					"SELECT COUNT(*) FROM `$sanitized_result_table` WHERE `class` = %d",
					$classId
				)
			);

			// Store in cache (5 minutes)
			wp_cache_set( $cache_key, $studentCount, 'rms', 300 );
		}

		return $studentCount;
	}

	/**
	 * astgdrmsys_render the dashboard header
	 */
	private function astgdrmsys_renderHeader() {
		?>
		<div class="premium-hero-banner">
			<div class="hero-content">
				<?php
				if ( ! empty( $this->schoolInfo ) ) :
					// If the logo path is stored as a relative path from uploads directory
					$upload_dir      = wp_upload_dir();
					$base_upload_dir = $upload_dir['basedir'];
					$relative_path = str_replace( $base_upload_dir . '/', '', $this->schoolInfo['logo'] );
					$logo_url = esc_url( $upload_dir['baseurl'] . '/' . $relative_path );
				?>
					<img class="hero-logo" onerror="this.style.display='none';" src="<?php echo esc_url( $logo_url ); ?>">
				<?php endif; ?>
				<div class="hero-text">
					<h1>Welcome to <?php echo !empty($this->schoolInfo['sc_name']) ? esc_html($this->schoolInfo['sc_name']) : 'Result Management System'; ?></h1>
					<p>Manage your students, classes, and results efficiently from one premium dashboard.</p>
				</div>
			</div>
			<div class="hero-actions">
				<a href="<?php echo esc_url(admin_url('admin.php?page=astgdrmsys-add-mark')); ?>" class="hero-btn primary-btn"><i class="dashicons dashicons-edit"></i> Add Marks</a>
				<a href="<?php echo esc_url(admin_url('admin.php?page=astgdrmsys-student-database&tab=add')); ?>" class="hero-btn secondary-btn"><i class="dashicons dashicons-welcome-add-page"></i> Add Student</a>
			</div>
		</div>
		<?php
	}

	/**
	 * astgdrmsys_render institute information section
	 */
	private function astgdrmsys_renderInstituteInfo() {
		?>
		<div class="info-section">
			<div class="section-header">
				<span>Institute Information</span>
				<a class="btn dash-btn" href="<?php echo esc_url( admin_url( 'admin.php?page=astgdrmsys-settings&option=school' ) ); ?>">Edit Institute</a>
			</div>
			<table class="styled-table">
				<thead>
					<tr>
						<th>Institute Name</th>
						<th>Address</th>
						<th>Contact No</th>
						<th>Website</th>
					</tr>
				</thead>
				<tbody>
					<?php if ( ! empty( $this->schoolInfo ) ) : ?>
						<tr>
							<td><?php echo esc_html( $this->schoolInfo['sc_name'] ); ?></td>
							<td>
								<?php
								echo esc_html(
									"{$this->schoolInfo['vill']}, {$this->schoolInfo['ps']}, " .
									"{$this->schoolInfo['dist']}, {$this->schoolInfo['pin']} " .
									"({$this->schoolInfo['state']})"
								);
								?>
							</td>
							<td><?php echo esc_html( $this->schoolInfo['phone'] ); ?></td>
							<td><?php echo esc_html( $this->schoolInfo['website'] ); ?></td>
						</tr>
					<?php else : ?>
						<tr>
							<td colspan="5" class="empty-text">No information added!</td>
						</tr>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * astgdrmsys_render class information section
	 */
	private function astgdrmsys_renderClassInfo( $wpdb ) {
		?>
		<div class="info-section">
			<div class="section-header">
				<span>Class Information</span>
				<a class="btn dash-btn" href="<?php echo esc_url( admin_url( 'admin.php?page=astgdrmsys-class' ) ); ?>">Add Class</a>
			</div>
			<table class="styled-table">
				<thead>
					<tr>
						<th>Class ID</th>
						<th>Class Name</th>
                                                <th>No. of Students</th>
					</tr>
				</thead>
				<tbody>
					<?php
					if ( ! empty( $this->classes ) ) :
                                                foreach ( $this->classes as $class ) :
                                                        $studentCount = $this->getStudentCount( $class['id'], $wpdb );
							?>
							<tr>
								<td><?php echo esc_html( $class['id'] ); ?></td>
								<td><?php echo esc_html( $class['class'] ); ?></td>
                                                                <td><?php echo esc_html( $studentCount ); ?></td>
							</tr>
							<?php
						endforeach;
					else :
						?>
                                                <tr>
                                                        <td colspan="3" class="empty-text">No class information available!</td>
						</tr>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * astgdrmsys_render the complete dashboard
	 */
	public function astgdrmsys_render() {
		?>
		<div class="astgdrmsys-dashboard-wrap astgdrmsys-premium-wrap">
			<?php
			$this->astgdrmsys_renderHeader();
			$this->astgdrmsys_renderInstituteInfo();
			$this->astgdrmsys_renderClassInfo( $this->wpdb );
                        ?>
                </div>
                <?php
        }
}

// Initialize and astgdrmsys_render the dashboard
$dashboard = new ASTGDRMSYS_Dashboard();
$dashboard->astgdrmsys_render();