<?php

/**
 * Class Page
 *
 * Maneja todas las operaciones de la base de datos para la tabla 'pages'.
 * Se encarga de leer y actualizar el contenido de las páginas estáticas del sitio.
 */
class Page
{
    // Conexión a la base de datos y nombre de la tabla
    private PDO $conn;
    private string $table_name = "pages";

    // Propiedades del objeto Page (mapeadas a las columnas de la tabla)
    public ?int $id = null;
    public ?string $page_key = null;
    public ?string $seo_title = null;
    public ?string $seo_description = null;
    public ?string $hero_headline = null;
    public ?string $hero_subheadline = null;
    public ?string $hero_cta_primary_text = null;
    public ?string $hero_cta_primary_href = null;
    public ?string $hero_cta_secondary_text = null;
    public ?string $hero_cta_secondary_href = null;
    public ?string $mission = null;
    public ?string $vision = null;
    public ?array $timeline = null;
    public ?array $team = null;
    public ?array $stats = null;

    /**
     * Constructor de la clase Page.
     * @param PDO $db La conexión activa a la base de datos.
     */
    public function __construct(PDO $db)
    {
        $this->conn = $db;
    }

    /**
     * Lee todos los registros de la tabla de páginas.
     * @return PDOStatement El statement de PDO con los resultados.
     */
    public function readAll(): PDOStatement
    {
        $query = "SELECT id, page_key, seo_title FROM " . $this->table_name . " ORDER BY page_key ASC";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }

    /**
     * Lee los datos de una única página basándose en su page_key.
     * Los datos leídos se asignan a las propiedades del objeto.
     * @return bool True si se encontró la página, false en caso contrario.
     */
    public function readOne(): bool
    {
        $query = "SELECT * FROM " . $this->table_name . " WHERE page_key = :page_key LIMIT 1";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':page_key', $this->page_key);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $this->id = (int)$row['id'];
            $this->seo_title = $row['seo_title'];
            $this->seo_description = $row['seo_description'];
            $this->hero_headline = $row['hero_headline'];
            $this->hero_subheadline = $row['hero_subheadline'];
            $this->hero_cta_primary_text = $row['hero_cta_primary_text'];
            $this->hero_cta_primary_href = $row['hero_cta_primary_href'];
            $this->hero_cta_secondary_text = $row['hero_cta_secondary_text'];
            $this->hero_cta_secondary_href = $row['hero_cta_secondary_href'];
            $this->mission = $row['mission'];
            $this->vision = $row['vision'];
            
            // Decodifica los campos JSON, asegurando un array vacío si el valor es NULL
            $this->timeline = json_decode($row['timeline'] ?? '[]', true);
            $this->team = json_decode($row['team'] ?? '[]', true);
            $this->stats = json_decode($row['stats'] ?? '[]', true);
            
            return true;
        }
        return false;
    }

    /**
     * Actualiza un registro de página en la base de datos.
     * Utiliza las propiedades del objeto para obtener los valores a actualizar.
     * @return bool True si la actualización fue exitosa, false en caso contrario.
     */
    public function update(): bool
    {
        $query = "UPDATE " . $this->table_name . "
                  SET
                      seo_title = :seo_title,
                      seo_description = :seo_description,
                      hero_headline = :hero_headline,
                      hero_subheadline = :hero_subheadline,
                      hero_cta_primary_text = :hero_cta_primary_text,
                      hero_cta_primary_href = :hero_cta_primary_href,
                      hero_cta_secondary_text = :hero_cta_secondary_text,
                      hero_cta_secondary_href = :hero_cta_secondary_href,
                      mission = :mission,
                      vision = :vision,
                      timeline = :timeline,
                      team = :team,
                      stats = :stats
                  WHERE page_key = :page_key";

        $stmt = $this->conn->prepare($query);

        // Limpia y prepara los datos para la actualización
        $this->seo_title = htmlspecialchars(strip_tags($this->seo_title));
        $this->seo_description = htmlspecialchars(strip_tags($this->seo_description));
        $this->hero_headline = htmlspecialchars(strip_tags($this->hero_headline));
        $this->hero_subheadline = htmlspecialchars(strip_tags($this->hero_subheadline));
        $this->hero_cta_primary_text = htmlspecialchars(strip_tags($this->hero_cta_primary_text));
        $this->hero_cta_primary_href = htmlspecialchars(strip_tags($this->hero_cta_primary_href));
        $this->hero_cta_secondary_text = htmlspecialchars(strip_tags($this->hero_cta_secondary_text));
        $this->hero_cta_secondary_href = htmlspecialchars(strip_tags($this->hero_cta_secondary_href));
        $this->mission = htmlspecialchars(strip_tags($this->mission));
        $this->vision = htmlspecialchars(strip_tags($this->vision));
        
        // Codifica los arrays a formato JSON para guardarlos en la base de datos
        $timelineJson = json_encode($this->timeline);
        $teamJson = json_encode($this->team);
        $statsJson = json_encode($this->stats);

        // Vincula los parámetros a la consulta
        $stmt->bindParam(':seo_title', $this->seo_title);
        $stmt->bindParam(':seo_description', $this->seo_description);
        $stmt->bindParam(':hero_headline', $this->hero_headline);
        $stmt->bindParam(':hero_subheadline', $this->hero_subheadline);
        $stmt->bindParam(':hero_cta_primary_text', $this->hero_cta_primary_text);
        $stmt->bindParam(':hero_cta_primary_href', $this->hero_cta_primary_href);
        $stmt->bindParam(':hero_cta_secondary_text', $this->hero_cta_secondary_text);
        $stmt->bindParam(':hero_cta_secondary_href', $this->hero_cta_secondary_href);
        $stmt->bindParam(':mission', $this->mission);
        $stmt->bindParam(':vision', $this->vision);
        $stmt->bindParam(':timeline', $timelineJson);
        $stmt->bindParam(':team', $teamJson);
        $stmt->bindParam(':stats', $statsJson);
        $stmt->bindParam(':page_key', $this->page_key);

        // Ejecuta la consulta
        if ($stmt->execute()) {
            return true;
        }

        return false;
    }
}