<?php

class Vendor {
    private $conn;
    private $table_name = "vendors";

    public $id_vendor;
    public $nama_vendor;
    public $jenis_layanan;
    public $pic_vendor;
    public $kontak_vendor;
    public $sla_uptime_percentage;
    public $sla_response_time_minutes;

    public function __construct($db) {
        $this->conn = $db;
    }
    
    public function create() {
        $query = "INSERT INTO " . $this->table_name . " SET nama_vendor=:nama_vendor, jenis_layanan=:jenis_layanan, pic_vendor=:pic_vendor, kontak_vendor=:kontak_vendor, sla_uptime_percentage=:sla_uptime_percentage, sla_response_time_minutes=:sla_response_time_minutes";
        $stmt = $this->conn->prepare($query);

        // Sanitize
        $this->nama_vendor=htmlspecialchars(strip_tags($this->nama_vendor));
        $this->jenis_layanan=htmlspecialchars(strip_tags($this->jenis_layanan));
        $this->pic_vendor=htmlspecialchars(strip_tags($this->pic_vendor));
        $this->kontak_vendor=htmlspecialchars(strip_tags($this->kontak_vendor));
        $this->sla_uptime_percentage=htmlspecialchars(strip_tags($this->sla_uptime_percentage));
        $this->sla_response_time_minutes=htmlspecialchars(strip_tags($this->sla_response_time_minutes));

        // Bind
        $stmt->bindParam(":nama_vendor", $this->nama_vendor);
        $stmt->bindParam(":jenis_layanan", $this->jenis_layanan);
        $stmt->bindParam(":pic_vendor", $this->pic_vendor);
        $stmt->bindParam(":kontak_vendor", $this->kontak_vendor);
        $stmt->bindParam(":sla_uptime_percentage", $this->sla_uptime_percentage);
        $stmt->bindParam(":sla_response_time_minutes", $this->sla_response_time_minutes);

        if($stmt->execute()){
            return true;
        }
        return false;
    }
    
    public function read() {
        $query = "SELECT * FROM " . $this->table_name . " ORDER BY nama_vendor ASC";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }

    // New method to get SLA performance for a specific vendor
    public function getSlaPerformance($id_vendor, $startDate, $endDate) {
        // Fetch vendor's SLA targets
        $query = "SELECT sla_uptime_percentage, sla_response_time_minutes FROM " . $this->table_name . " WHERE id_vendor = ? LIMIT 0,1";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $id_vendor);
        $stmt->execute();
        $vendorSla = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$vendorSla) {
            return false; // Vendor not found
        }

        // Fetch incidents for the vendor within the date range
        $queryIncidents = "SELECT waktu_mulai, waktu_selesai, durasi_downtime_minutes 
                           FROM sla_incidents 
                           WHERE id_vendor = :id_vendor 
                           AND waktu_mulai BETWEEN :start_date AND :end_date 
                           ORDER BY waktu_mulai ASC";
        
        $stmtIncidents = $this->conn->prepare($queryIncidents);
        $stmtIncidents->bindParam(':id_vendor', $id_vendor);
        $stmtIncidents->bindParam(':start_date', $startDate);
        $stmtIncidents->bindParam(':end_date', $endDate);
        $stmtIncidents->execute();
        $incidents = $stmtIncidents->fetchAll(PDO::FETCH_ASSOC);

        $totalDowntimeMinutes = 0;
        $slaBreaches = 0; // Number of incidents that explicitly breach an SLA (e.g., > 0 downtime)

        foreach ($incidents as $incident) {
            $totalDowntimeMinutes += (int)$incident['durasi_downtime_minutes'];
            // Simple breach logic: any downtime is a breach for uptime percentage
            if ((int)$incident['durasi_downtime_minutes'] > 0) {
                $slaBreaches++;
            }
            // Future: could add more complex logic for response time if a field is added
        }

        // Calculate total minutes in the period (assuming 24/7 operation for uptime)
        $startDateTime = new DateTime($startDate);
        $endDateTime = new DateTime($endDate);
        $interval = $startDateTime->diff($endDateTime);
        $totalMinutesInPeriod = ($interval->days * 24 * 60) + ($interval->h * 60) + $interval->i;
        
        // Avoid division by zero if period is too short or invalid
        $actualUptimePercentage = 100;
        if ($totalMinutesInPeriod > 0) {
            $actualUptime = ($totalMinutesInPeriod - $totalDowntimeMinutes);
            $actualUptimePercentage = ($actualUptime / $totalMinutesInPeriod) * 100;
        }

        return [
            'vendor_sla_uptime_percentage' => $vendorSla['sla_uptime_percentage'],
            'vendor_sla_response_time_minutes' => $vendorSla['sla_response_time_minutes'],
            'total_downtime_minutes' => $totalDowntimeMinutes,
            'number_of_incidents' => count($incidents),
            'number_of_sla_breaches' => $slaBreaches,
            'actual_uptime_percentage' => round($actualUptimePercentage, 2)
        ];
    }
}
