<?php

class SlaIncident {
    private $conn;
    private $table_name = "sla_incidents";

    public $id_incident;
    public $id_vendor;
    public $incident_description;
    public $waktu_mulai;
    public $waktu_selesai;
    public $durasi_downtime_minutes;

    public function __construct($db) {
        $this->conn = $db;
    }

    public function create() {
        $query = "INSERT INTO " . $this->table_name . " SET id_vendor=:id_vendor, incident_description=:incident_description, waktu_mulai=:waktu_mulai";
        $stmt = $this->conn->prepare($query);

        // Sanitize
        $this->id_vendor=htmlspecialchars(strip_tags($this->id_vendor));
        $this->incident_description=htmlspecialchars(strip_tags($this->incident_description));
        $this->waktu_mulai=htmlspecialchars(strip_tags($this->waktu_mulai));

        // Bind
        $stmt->bindParam(":id_vendor", $this->id_vendor);
        $stmt->bindParam(":incident_description", $this->incident_description);
        $stmt->bindParam(":waktu_mulai", $this->waktu_mulai);

        if($stmt->execute()){
            return true;
        }
        return false;
    }

    public function readByVendor($id_vendor) {
        $query = "SELECT i.*, v.nama_vendor FROM " . $this->table_name . " i LEFT JOIN vendors v ON i.id_vendor = v.id_vendor WHERE i.id_vendor = ? ORDER BY i.waktu_mulai DESC";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $id_vendor);
        $stmt->execute();
        return $stmt;
    }
    
    public function readAll() {
        $query = "SELECT i.*, v.nama_vendor FROM " . $this->table_name . " i LEFT JOIN vendors v ON i.id_vendor = v.id_vendor ORDER BY i.waktu_mulai DESC";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }

    // Mark an incident as resolved
    public function resolve() {
        $query = "UPDATE " . $this->table_name . "
                  SET
                    waktu_selesai = :waktu_selesai,
                    durasi_downtime_minutes = :durasi_downtime_minutes
                  WHERE
                    id_incident = :id_incident";
        
        $stmt = $this->conn->prepare($query);

        // Sanitize
        $this->waktu_selesai=htmlspecialchars(strip_tags($this->waktu_selesai));
        $this->durasi_downtime_minutes=htmlspecialchars(strip_tags($this->durasi_downtime_minutes));
        $this->id_incident=htmlspecialchars(strip_tags($this->id_incident));

        // Bind
        $stmt->bindParam(':waktu_selesai', $this->waktu_selesai);
        $stmt->bindParam(':durasi_downtime_minutes', $this->durasi_downtime_minutes);
        $stmt->bindParam(':id_incident', $this->id_incident);

        if($stmt->execute()){
            return true;
        }
        return false;
    }
}
