<?php
require_once __DIR__ . '/../config/db_config.php';

class Product {
    private $conn;
    private $table = 'products';

    // Product properties
    public $product_id;
    public $name;
    public $description;
    public $price;
    public $stock;
    public $image;
    public $is_active;
    public $created_at;
    public $updated_at;

    /**
     * Constructor with DB connection
     */
    public function __construct() {
        $this->conn = getDbConnection();
    }

    /**
     * Check if database connection is available
     * 
     * @return boolean True if connection exists, false otherwise
     */
    private function checkConnection() {
        if ($this->conn === null) {
            error_log("Database connection failed in Product model");
            return false;
        }
        return true;
    }

    /**
     * Get all active products
     * 
     * @return array Array of products or empty array if none found or connection failed
     */
    public function getAllProducts() {
        if (!$this->checkConnection()) {
            return [];
        }

        try {
            $query = "SELECT * FROM " . $this->table . " WHERE is_active = true ORDER BY created_at DESC";
            $stmt = $this->conn->prepare($query);
            $stmt->execute();
            
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error getting products: " . $e->getMessage());
            return [];
        }
    }

    /**
     * Get single product by ID
     * 
     * @param int $id Product ID
     * @return array|false Product array or false if not found
     */
    public function getProductById($id) {
        if (!$this->checkConnection()) {
            return false;
        }

        try {
            $query = "SELECT * FROM " . $this->table . " WHERE product_id = :id AND is_active = true LIMIT 1";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error getting product by ID: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Create new product
     * 
     * @return boolean True on success, false on failure
     */
    public function create() {
        if (!$this->checkConnection()) {
            return false;
        }

        try {
            $query = "INSERT INTO " . $this->table . " 
                    (name, description, price, stock, image, is_active) 
                    VALUES 
                    (:name, :description, :price, :stock, :image, :is_active)";
            
            $stmt = $this->conn->prepare($query);
            
            // Sanitize and bind data
            $this->name = htmlspecialchars(strip_tags($this->name));
            $this->description = htmlspecialchars(strip_tags($this->description));
            
            $stmt->bindParam(':name', $this->name);
            $stmt->bindParam(':description', $this->description);
            $stmt->bindParam(':price', $this->price);
            $stmt->bindParam(':stock', $this->stock);
            $stmt->bindParam(':image', $this->image);
            $stmt->bindParam(':is_active', $this->is_active);
            
            if ($stmt->execute()) {
                $this->product_id = $this->conn->lastInsertId();
                return true;
            }
            
            return false;
        } catch (PDOException $e) {
            error_log("Error creating product: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Update product
     * 
     * @return boolean True on success, false on failure
     */
    public function update() {
        if (!$this->checkConnection()) {
            return false;
        }

        try {
            $query = "UPDATE " . $this->table . " 
                    SET 
                    name = :name, 
                    description = :description, 
                    price = :price, 
                    stock = :stock, 
                    image = :image, 
                    is_active = :is_active 
                    WHERE 
                    product_id = :id";
                    
            $stmt = $this->conn->prepare($query);
            
            // Sanitize and bind data
            $this->name = htmlspecialchars(strip_tags($this->name));
            $this->description = htmlspecialchars(strip_tags($this->description));
            
            $stmt->bindParam(':name', $this->name);
            $stmt->bindParam(':description', $this->description);
            $stmt->bindParam(':price', $this->price);
            $stmt->bindParam(':stock', $this->stock);
            $stmt->bindParam(':image', $this->image);
            $stmt->bindParam(':is_active', $this->is_active);
            $stmt->bindParam(':id', $this->product_id);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error updating product: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Delete product (soft delete by setting is_active to false)
     * 
     * @param int $id Product ID
     * @return boolean True on success, false on failure
     */
    public function delete($id) {
        if (!$this->checkConnection()) {
            return false;
        }

        try {
            $query = "UPDATE " . $this->table . " SET is_active = false WHERE product_id = :id";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':id', $id);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error deleting product: " . $e->getMessage());
            return false;
        }
    }
} 