<?php

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

class SLAController {
    private $conn;
    private $vendor;
    private $incident;

    public function __construct() {
        $this->conn = connectDB();
        $this->vendor = new Vendor($this->conn);
        $this->incident = new SlaIncident($this->conn);
    }

    public function index() {
        $this->showVendors();
    }

    public function showVendors() {
        $vendors = $this->vendor->read()->fetchAll(PDO::FETCH_ASSOC);
        require_once dirname(__DIR__) . '/../views/sla/vendors/index.php';
    }


    public function showAddVendorForm() {
        require_once dirname(__DIR__) . '/../views/sla/vendors/create.php';
    }

    public function showIncidents() {
        $incidents = $this->incident->readAll()->fetchAll(PDO::FETCH_ASSOC);
        // Also need a list of vendors for the incident form (dropdown)
        $vendors_for_incident_form = $this->vendor->read()->fetchAll(PDO::FETCH_ASSOC);
        require_once dirname(__DIR__) . '/../views/sla/incidents/index.php';
    }

    public function showAddIncidentForm() {
        $vendors_for_incident_form = $this->vendor->read()->fetchAll(PDO::FETCH_ASSOC); // Needed for dropdown
        require_once dirname(__DIR__) . '/../views/sla/incidents/create.php';
    }

    public function processAddVendor() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->vendor->nama_vendor = $_POST['nama_vendor'];
            $this->vendor->jenis_layanan = $_POST['jenis_layanan'];
            $this->vendor->kontak_vendor = $_POST['kontak_vendor'];
            $this->vendor->sla_uptime_percentage = $_POST['sla_uptime_percentage'];
            $this->vendor->sla_response_time_minutes = $_POST['sla_response_time_minutes'];
            if ($this->vendor->create()) {
                header("Location: ?page=sla_vendors&message=vendor_added");
            } else {
                header("Location: ?page=sla_vendors_create&error=add_failed");
            }
            exit();
        }
    }

    public function processAddIncident() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->incident->id_vendor = $_POST['id_vendor'];
            $this->incident->incident_description = $_POST['incident_description'];
            $this->incident->waktu_mulai = $_POST['waktu_mulai'];
            if ($this->incident->create()) {
                header("Location: ?page=sla_incidents&message=incident_added");
            } else {
                header("Location: ?page=sla_incidents_create&error=add_failed");
            }
            exit();
        }
    }

    public function processResolveIncident() {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->incident->id_incident = $_POST['id_incident'];
            $this->incident->waktu_selesai = date('Y-m-d H:i:s');
            
            $waktu_mulai = new DateTime($_POST['waktu_mulai']);
            $waktu_selesai = new DateTime($this->incident->waktu_selesai);
            $diff = $waktu_selesai->getTimestamp() - $waktu_mulai->getTimestamp();
            $this->incident->durasi_downtime_minutes = round($diff / 60);
            
            if ($this->incident->resolve()) {
                header("Location: ?page=sla_incidents&message=incident_resolved");
            } else {
                header("Location: ?page=sla_incidents&error=resolve_failed");
            }
            exit();
        }
    }

    public function vendorPerformance() {
        // Set default date range for performance calculation
        $endDate = date('Y-m-d H:i:s');
        $startDate = date('Y-m-d H:i:s', strtotime('-30 days', strtotime($endDate))); // Last 30 days

        $allVendors = $this->vendor->read()->fetchAll(PDO::FETCH_ASSOC);
        $performanceData = [];

        foreach ($allVendors as $vendor) {
            $vendorId = $vendor['id_vendor'];
            $performance = $this->vendor->getSlaPerformance($vendorId, $startDate, $endDate);
            if ($performance) {
                $performanceData[$vendorId] = array_merge($vendor, $performance);
            } else {
                // Handle cases where vendor might not have incidents or Sla data
                $performanceData[$vendorId] = $vendor;
                $performanceData[$vendorId]['total_downtime_minutes'] = 0;
                $performanceData[$vendorId]['number_of_incidents'] = 0;
                $performanceData[$vendorId]['number_of_sla_breaches'] = 0;
                $performanceData[$vendorId]['actual_uptime_percentage'] = 100; // Assume 100% if no incidents
            }
        }
        
        // Pass data to the view
        require_once dirname(__DIR__) . '/../views/sla/vendor_performance.php';
    }
}
