<?php

require_once dirname(__DIR__) . '/models/RoomTemperature.php';
require_once dirname(__DIR__) . '/../config/db.php';

class RoomTemperatureController {
    private $conn;
    private $roomTemperature;

    public function __construct() {
        $this->conn = connectDB();
        $this->roomTemperature = new RoomTemperature($this->conn);
    }

    public function index() {
        // Fetch the latest temperature and humidity data
        $latestReading = null;
        if ($this->roomTemperature->getLatest()) {
            $latestReading = [
                'temperature' => $this->roomTemperature->temperature,
                'humidity' => $this->roomTemperature->humidity,
                'recorded_at' => $this->roomTemperature->recorded_at
            ];
        }

        // Define national indicators for server room (example values)
        $nationalIndicator = [
            'normal_temperature_min' => 18, // Celsius
            'normal_temperature_max' => 27, // Celsius
            'normal_humidity_min' => 40,    // %
            'normal_humidity_max' => 60     // %
        ];

        // Pass data to the view
        require_once dirname(__DIR__, 2) . '/views/room_temperature/index.php';
    }

    public function history() {
        $year = $_GET['year'] ?? date('Y');
        $month = $_GET['month'] ?? date('m');

        // Fetch historical data for the selected month and year
        $stmt = $this->roomTemperature->readByMonth($year, $month);
        $historyData = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Prepare data for calendar display (group by day)
        $calendarData = [];
        foreach ($historyData as $record) {
            $day = date('d', strtotime($record['recorded_at']));
            if (!isset($calendarData[$day])) {
                $calendarData[$day] = [];
            }
            $calendarData[$day][] = $record;
        }

        // Pass data to the view
        require_once dirname(__DIR__, 2) . '/views/room_temperature/history.php';
    }

    // Show form for manual temperature and humidity input
    public function showInputForm() {
        require_once dirname(__DIR__, 2) . '/views/room_temperature/input_form.php';
    }

    // Process manual temperature and humidity input
    public function addReading() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->roomTemperature->temperature = $_POST['temperature'] ?? null;
            $this->roomTemperature->humidity = $_POST['humidity'] ?? null;

            if (empty($this->roomTemperature->temperature) || empty($this->roomTemperature->humidity)) {
                header("Location: ?page=room_temperature_input&error=empty_fields");
                exit();
            }

            if (!is_numeric($this->roomTemperature->temperature) || !is_numeric($this->roomTemperature->humidity)) {
                header("Location: ?page=room_temperature_input&error=invalid_data");
                exit();
            }

            if ($this->roomTemperature->create()) {
                header("Location: ?page=room_temperature&message=input_success");
                exit();
            } else {
                header("Location: ?page=room_temperature_input&error=save_failed");
                exit();
            }
        } else {
            header("Location: ?page=room_temperature_input");
            exit();
        }
    }

    // Public method to display monthly temperature report, accessible without login
    public function publicMonthlyReport() {
        $year = $_GET['year'] ?? date('Y');
        $month = $_GET['month'] ?? date('m');

        // Fetch historical data for the selected month and year
        $stmt = $this->roomTemperature->readByMonth($year, $month);
        $historyData = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Prepare data for calendar display (group by day)
        $calendarData = [];
        foreach ($historyData as $record) {
            $day = date('d', strtotime($record['recorded_at']));
            if (!isset($calendarData[$day])) {
                $calendarData[$day] = [];
            }
            $calendarData[$day][] = $record;
        }

        // Define national indicators for server room (example values, consistent with index)
        $nationalIndicator = [
            'normal_temperature_min' => 18, // Celsius
            'normal_temperature_max' => 27, // Celsius
            'normal_humidity_min' => 40,    // %
            'normal_humidity_max' => 60     // %
        ];

        // Pass data to the view
        require_once dirname(__DIR__, 2) . '/views/room_temperature/public_monthly_report.php';
    }
}
