<?php

class Contactus {
    private $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    /**
     * Submits a new feedback message from a user/visitor.
     *
     * @param string $name The name of the person submitting feedback.
     * @param string|null $email The email of the person, if provided.
     * @param string $body_text The main body of the feedback message.
     * @param string|null $client_ip The IP address of the client.
     * @return bool True on success.
     * @throws Exception If a database error occurs.
     */
    public function submitFeedback(string $name, ?string $email, string $body_text, ?string $client_ip): bool {
        $sql = "INSERT INTO dsps_tbl_feedback (dspsfb_name, dspsfb_email, dspsfb_body_text, dspsfb_client_ip, dspsfb_status)
                VALUES (:name, :email, :body_text, :client_ip, 'New')";
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':name', $name);
            $stmt->bindParam(':email', $email);
            $stmt->bindParam(':body_text', $body_text);
            $stmt->bindParam(':client_ip', $client_ip);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error submitting feedback: " . $e->getMessage());
            throw new Exception("Could not submit feedback. Please try again later.");
        }
    }

    /**
     * Allows a DAC Staff user to respond to a feedback message.
     *
     * @param int $feedback_id The ID of the feedback message to respond to.
     * @param string $respond_text The response text from the DAC Staff.
     * @param string $status The new status of the feedback (e.g., 'In Progress', 'Resolved').
     * @param int $res_by The user ID of the DAC Staff who responded.
     * @return bool True on success.
     * @throws Exception If a database error occurs.
     */
    public function respondToFeedback(int $feedback_id, string $respond_text, string $status, int $res_by): bool {
        $sql = "UPDATE dsps_tbl_feedback
                SET dspsfb_respond_text = :respond_text, dspsfb_status = :status,
                    dspsfb_res_datetime = CURRENT_TIMESTAMP, dspsfb_res_by = :res_by
                WHERE pkdspsfb_id = :feedback_id";
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':respond_text', $respond_text);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':res_by', $res_by);
            $stmt->bindParam(':feedback_id', $feedback_id);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error responding to feedback (ID: $feedback_id): " . $e->getMessage());
            throw new Exception("Could not respond to feedback. Please try again later.");
        }
    }

    /**
     * Deletes a feedback message.
     *
     * @param int $feedback_id The ID of the feedback message to delete.
     * @return bool True on success.
     * @throws Exception If a database error occurs.
     */
    public function deleteFeedback(int $feedback_id): bool {
        $sql = "DELETE FROM dsps_tbl_feedback WHERE pkdspsfb_id = :feedback_id";
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':feedback_id', $feedback_id);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error deleting feedback (ID: $feedback_id): " . $e->getMessage());
            throw new Exception("Could not delete feedback. Please try again later.");
        }
    }

    /**
     * Retrieves a single feedback message by its ID.
     *
     * @param int $feedback_id The ID of the feedback message.
     * @return array|false The feedback data as an associative array, or false if not found.
     * @throws Exception If a database error occurs.
     */
    public function getFeedbackById(int $feedback_id) {
        $sql = "SELECT * FROM dsps_tbl_feedback WHERE pkdspsfb_id = :feedback_id";
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->bindParam(':feedback_id', $feedback_id);
            $stmt->execute();
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error fetching feedback by ID ($feedback_id): " . $e->getMessage());
            throw new Exception("Could not retrieve feedback. Please try again later.");
        }
    }

    /**
     * Retrieves all feedback messages, optionally filtered by status.
     *
     * @param string|null $status Optional status to filter by (e.g., 'New', 'Resolved').
     * @return array An array of feedback data.
     * @throws Exception If a database error occurs.
     */
    public function getAllFeedback(?string $status = null): array {
        $sql = "SELECT * FROM dsps_tbl_feedback";
        $conditions = [];
        $params = [];

        if ($status) {
            $conditions[] = "dspsfb_status = :status";
            $params[':status'] = $status;
        }

        if (!empty($conditions)) {
            $sql .= " WHERE " . implode(" AND ", $conditions);
        }

        $sql .= " ORDER BY dspsfb_reg_datetime DESC";

        try {
            $stmt = $this->pdo->prepare($sql);
            foreach ($params as $key => &$val) {
                $stmt->bindParam($key, $val, is_int($val) ? PDO::PARAM_INT : PDO::PARAM_STR);
            }
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error fetching all feedback: " . $e->getMessage());
            throw new Exception("Could not retrieve feedback messages. Please try again later.");
        }
    }

    /**
     * Gets the total count of feedback messages, optionally filtered by status.
     *
     * @param string|null $status Optional status to filter by.
     * @return int The total number of feedback messages.
     * @throws Exception If a database error occurs.
     */
    public function getTotalFeedback(?string $status = null): int {
        $sql = "SELECT COUNT(*) FROM dsps_tbl_feedback";
        $conditions = [];
        $params = [];

        if ($status) {
            $conditions[] = "dspsfb_status = :status";
            $params[':status'] = $status;
        }

        if (!empty($conditions)) {
            $sql .= " WHERE " . implode(" AND ", $conditions);
        }

        try {
            $stmt = $this->pdo->prepare($sql);
            foreach ($params as $key => &$val) {
                $stmt->bindParam($key, $val, is_int($val) ? PDO::PARAM_INT : PDO::PARAM_STR);
            }
            $stmt->execute();
            return $stmt->fetchColumn();
        } catch (PDOException $e) {
            error_log("Error getting total feedback count: " . $e->getMessage());
            throw new Exception("Could not retrieve feedback count. Please try again later.");
        }
    }
}
