<?php
// models/Prevention.php

/**
 * Prevention Model for Rehlko Customer Care application.
 * Manages CRUD operations and data interaction for the 'prevention' table.
 */
class Prevention {
    private $conn;
    private $table_name = "prevention";

    // Object properties
    public $id;
    public $report_index;
    public $prevention_title;
    public $created_user;
    public $created_datetime;
    public $modified_datetime;

    /**
     * Constructor for the Prevention model.
     *
     * @param mysqli $db The database connection object.
     */
    public function __construct($db) {
        $this->conn = $db;
    }

    /**
     * Creates a new prevention record.
     *
     * @return bool True on success, false on failure.
     */
    public function create() {
        $query = "INSERT INTO " . $this->table_name . "
                  SET report_index=?, prevention_title=?, created_user=?";

        $stmt = $this->conn->prepare($query);
        if ($stmt === false) {
            error_log("Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error);
            return false;
        }

        // Sanitize inputs
        $this->report_index = htmlspecialchars(strip_tags($this->report_index));
        $this->prevention_title = htmlspecialchars(strip_tags($this->prevention_title));
        $this->created_user = htmlspecialchars(strip_tags($this->created_user));

        $stmt->bind_param("ssi", $this->report_index, $this->prevention_title, $this->created_user);

        if ($stmt->execute()) {
            $this->id = $this->conn->insert_id;
            return true;
        }
        error_log("Prevention creation failed: (" . $stmt->errno . ") " . $stmt->error);
        return false;
    }

    /**
     * Reads prevention records for a specific report index.
     *
     * @param string $reportIndex The report index to filter by.
     * @return array An array of prevention records.
     */
    public function readByReportIndex($reportIndex) {
        $query = "SELECT prev.id, prev.report_index, prev.prevention_title, prev.created_user,u.fullname as created_user_name, prev.created_datetime, prev.modified_datetime
                  FROM " . $this->table_name . " AS prev
                  INNER JOIN users AS u ON prev.created_user = u.id
                  WHERE prev.report_index = ?
                  ORDER BY prev.created_datetime ASC";

        $stmt = $this->conn->prepare($query);
        if ($stmt === false) {
            error_log("Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error);
            return [];
        }

        $reportIndex = htmlspecialchars(strip_tags($reportIndex));
        $stmt->bind_param("s", $reportIndex);

        if ($stmt->execute()) {
            $result = $stmt->get_result();
            $preventionActions = [];
            while ($row = $result->fetch_assoc()) {
                $preventionActions[] = $row;
            }
            return $preventionActions;
        }
        error_log("Read prevention actions by report index failed: (" . $stmt->errno . ") " . $stmt->error);
        return [];
    }

    /**
     * Reads a single prevention record by ID.
     *
     * @return array|false The prevention data as an associative array on success, false if not found.
     */
    public function readOne() {
        $query = "SELECT id, report_index, prevention_title, created_user, created_datetime, modified_datetime
                  FROM " . $this->table_name . "
                  WHERE id = ? LIMIT 0,1";

        $stmt = $this->conn->prepare($query);
        if ($stmt === false) {
            error_log("Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error);
            return false;
        }

        $this->id = htmlspecialchars(strip_tags($this->id));
        $stmt->bind_param("i", $this->id);

        if ($stmt->execute()) {
            $result = $stmt->get_result();
            return $result->fetch_assoc();
        }
        error_log("Read one prevention failed: (" . $stmt->errno . ") " . $stmt->error);
        return false;
    }

    /**
     * Updates an existing prevention record.
     *
     * @return bool True on success, false on failure.
     */
    public function update() {
        $query = "UPDATE " . $this->table_name . "
                  SET prevention_title=?
                  WHERE id=?";

        $stmt = $this->conn->prepare($query);
        if ($stmt === false) {
            error_log("Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error);
            return false;
        }

        // Sanitize inputs
        $this->prevention_title = htmlspecialchars(strip_tags($this->prevention_title));
        $this->id = htmlspecialchars(strip_tags($this->id));

        $stmt->bind_param("si", $this->prevention_title, $this->id);

        if ($stmt->execute()) {
            return true;
        }
        error_log("Prevention update failed: (" . $stmt->errno . ") " . $stmt->error);
        return false;
    }

    /**
     * Deletes a prevention record by ID.
     *
     * @return bool True on success, false on failure.
     */
    public function delete() {
        $query = "DELETE FROM " . $this->table_name . " WHERE id = ?";

        $stmt = $this->conn->prepare($query);
        if ($stmt === false) {
            error_log("Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error);
            return false;
        }

        $this->id = htmlspecialchars(strip_tags($this->id));
        $stmt->bind_param("i", $this->id);

        if ($stmt->execute()) {
            return true;
        }
        error_log("Prevention deletion failed: (" . $stmt->errno . ") " . $stmt->error);
        return false;
    }
}
?>
