<?php
// Player.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class Player
{
    private $conn;

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

    public function getAllPlayers()
    {
        $sql = "SELECT id, pNombre, pApellido FROM player WHERE state = 1";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }

    public function getPlayerById($id)
    {
        $sql = "SELECT * FROM player WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

    public function getPlayerByCode($code)
    {
        $sql = "SELECT id, pNombre, pApellido FROM player WHERE code = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $code);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc();
    }

    public function getPlayerCodeById($id)
    {
        $sql = "SELECT code FROM player WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc()['code'] ?? null;
    }

    public function getPlayerIdByCode($code)
    {
        $sql = "SELECT id FROM player WHERE code = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $code);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc()['id'] ?? null;
    }

    public function getPlayerPicById($id)
    {
        $sql = "SELECT pic FROM player WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        return $stmt->get_result()->fetch_assoc()['pic'] ?? null;
    }


    public function createPlayer($data)
{
    $sql = "INSERT INTO player (code, pNombre, sNombre, pApellido, mApellido, direccion, categoria, `description`, instagram)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $this->conn->prepare($sql);
    
    if ($stmt === false) {
        // Return preparation error (if the query itself has an issue)
        return "Prepare failed: (" . $this->conn->errno . ") " . $this->conn->error;
    }

    $stmt->bind_param(
        'sssssssss',
        $data['code'],
        $data['pNombre'],
        $data['sNombre'],
        $data['pApellido'],
        $data['mApellido'],
        $data['direccion'],
        $data['categoria'],
        $data['description'],
        $data['instagram']
    );
    
    if ($stmt->execute()) {
        return "true";
    } else {
        // Return execution error (if the query fails to execute)
        return "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
}


   public function updatePlayer($data)
{
    // Validar datos obligatorios
    if (empty($data['pNombre']) || empty($data['pApellido']) || !isset($data['id'])) {
        return ["error" => "Faltan datos obligatorios para actualizar el jugador."];
    }

    // Preparar la consulta SQL
    $sql = "UPDATE player SET 
                pNombre = ?, 
                sNombre = ?, 
                pApellido = ?, 
                mApellido = ?, 
                direccion = ?, 
                categoria = ?, 
                `description` = ?, 
                instagram = ?, 
                racket = ? 
            WHERE id = ?";

    $stmt = $this->conn->prepare($sql);
    if ($stmt === false) {
        return ["error" => "Error al preparar la consulta: " . $this->conn->error];
    }

    // Almacenar los parámetros en variables
    $pNombre = $data['pNombre'];
    $sNombre = isset($data['sNombre']) ? $data['sNombre'] : null; // Puede ser null
    $pApellido = $data['pApellido'];
    $mApellido = isset($data['mApellido']) ? $data['mApellido'] : null; // Puede ser null
    $direccion = isset($data['direccion']) ? $data['direccion'] : null; // Puede ser null
    $categoria = $data['categoria'];
    $description = isset($data['description']) ? $data['description'] : null; // Puede ser null
    $instagram = isset($data['instagram']) ? $data['instagram'] : null; // Puede ser null
    $racket = isset($data['racket']) ? $data['racket'] : null; // Puede ser null
    $id = $data['id'];

    // Vincular parámetros (actualiza la cadena de tipos)
    $stmt->bind_param(
        'sssssssssi', // Se agregó 'i' al final para el parámetro id que es un entero
        $pNombre,
        $sNombre,
        $pApellido,
        $mApellido,
        $direccion,
        $categoria,
        $description,
        $instagram,
        $racket,
        $id // Este es el último parámetro y debe ser un entero
    );

    // Ejecutar la consulta
    $result = $stmt->execute();
    if ($result) {
        return ["success" => true, "affected_rows" => $stmt->affected_rows];
    } else {
        return ["error" => "Error al ejecutar la consulta: " . $stmt->error];
    }
}


    public function updatePlayerPic($id, $imgid)
    {
        $sql = "UPDATE player SET pic = ? WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('si', $imgid, $id);
        if ($stmt->execute()) {
            return true;
        }
    }
}
