<?php

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

class KpiController {
    private $conn;
    private $kpi;
    private $kpiManualInput;

    public function __construct() {
        $this->conn = connectDB();
        $this->kpi = new Kpi($this->conn);
        $this->kpiManualInput = new KpiManualInput($this->conn);
    }

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

        // Ensure month and year are valid integers
        $filterMonth = (int)$filterMonth;
        $filterYear = (int)$filterYear;
        if ($filterMonth < 1 || $filterMonth > 12) $filterMonth = (int)date('m');
        if ($filterYear < 1900 || $filterYear > 2100) $filterYear = (int)date('Y');


        // Fetch KPI values
        $kpi_device_damage_percentage = $this->kpi->calculateDeviceDamagePercentage(); // Does not use month/year
        
        $kpi_ink_procurement_cost_val = $this->kpiManualInput->read('Biaya Pengadaan Tinta', $filterMonth, $filterYear);
        $kpi_ink_procurement_cost = $kpi_ink_procurement_cost_val !== null ? (float)$kpi_ink_procurement_cost_val : 0;
        
        $kpi_customer_satisfaction = $this->kpi->getCustomerSatisfaction($filterMonth, $filterYear);
        // If monthly customer satisfaction is desired, getCustomerSatisfaction() in Kpi.php
        // and getAverageRating() in Survey.php would need modification.
        // For now, it will remain overall satisfaction.

        $kpi_avg_helpdesk_response_time = $this->kpi->getAvgHelpdeskResponseTime($filterMonth, $filterYear);
        // If monthly average response time is desired, getAvgHelpdeskResponseTime() in Kpi.php
        // would need modification.

        $kpi_system_change_socialization = $this->kpiManualInput->read('Sosialisasi Perubahan Sistem', $filterMonth, $filterYear) ?? 'Manual';
        
        $kpi_preventive_maintenance_percentage = $this->kpi->calculatePreventiveMaintenancePercentage($filterMonth, $filterYear);
        
        $kpi_5r_implementation = $this->kpiManualInput->read('Penerapan 5R', $filterMonth, $filterYear) ?? 'Manual';
        
        $kpi_downtime_result = $this->kpi->calculateDowntimeKPI($filterMonth, $filterYear);
        
        $kpi_lean_management_implementation = $this->kpiManualInput->read('Implementasi Kaizen', $filterMonth, $filterYear) ?? 'Manual';

        // Pass filter values to the view
        $filters = [
            'month' => $filterMonth,
            'year' => $filterYear
        ];

        require_once dirname(__DIR__) . '/../views/kpi/index.php';
    }

    public function showManualInputForm() {
        $history = [];
        if (isset($_SESSION['user_id'])) {
            $history = $this->kpiManualInput->getHistoryByUser($_SESSION['user_id']);
        }
        require_once dirname(__DIR__) . '/../views/kpi/manual_input_form.php';
    }

    public function processManualInput() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if (!isset($_SESSION['user_id'])) {
                header("Location: ?page=login&error=not_logged_in");
                exit();
            }

            $kpi_name = htmlspecialchars(strip_tags($_POST['kpi_name']));
            
            $value_raw = $_POST['value'];
            // Clean the value: remove "Rp.", thousands separators (.), and potentially decimal commas (,)
            $value_cleaned = str_replace(['Rp.', '.', ','], '', $value_raw);
            $value = (float)htmlspecialchars(strip_tags($value_cleaned)); // Ensure it's a float

            $month = htmlspecialchars(strip_tags($_POST['month'])); // Should be int
            $year = htmlspecialchars(strip_tags($_POST['year']));   // Should be int
            $input_by_user_id = htmlspecialchars(strip_tags($_SESSION['user_id'])); // Should be int

            // Ensure month, year, user_id are integers
            $month = (int)$month;
            $year = (int)$year;
            $input_by_user_id = (int)$input_by_user_id;

            if (empty($kpi_name) || empty($value) || empty($month) || empty($year)) {
                header("Location: ?page=kpi_manual_input_form&error=empty_fields");
                exit();
            }

            $this->kpiManualInput->kpi_name = $kpi_name;
            $this->kpiManualInput->value = $value;
            $this->kpiManualInput->month = $month;
            $this->kpiManualInput->year = $year;
            $this->kpiManualInput->input_by_user_id = $input_by_user_id;

            if ($this->kpiManualInput->createOrUpdate()) {
                header("Location: ?page=kpi_it&message=input_success");
                exit();
            } else {
                header("Location: ?page=kpi_manual_input_form&error=input_failed");
                exit();
            }
        }
    }
}