<?php
include_once '../../config/Database.php';

class EstudianteController
{
    private $db;

    public function __construct()
    {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    public function listarEstudiantes()
    {
        try {
            $query = "SELECT * FROM student";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al listar estudiantes: " . $e->getMessage());
            return [];
        }
    }

    public function listarEstudiantesPorFecha($fechaInicio, $fechaFin)
    {
        try {
            $query = "SELECT * FROM student WHERE DATE(fecha_reg) BETWEEN :fechaInicio AND :fechaFin";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':fechaInicio', $fechaInicio);
            $stmt->bindParam(':fechaFin', $fechaFin);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al listar estudiantes por fecha: " . $e->getMessage());
            return [];
        }
    }

    public function agregarEstudiante($Cod_Estu, $emailid, $sname, $contrasena, $ci, $exp_ci, $joindate, $about, $contact, $fees, $branch, $balance, $carrera, $curso, $turno, $modalidad, $sucursal_varchar)
    {
        try {
            $datos = [
                'Cod_Estu' => $Cod_Estu,
                'emailid' => $emailid,
                'sname' => $sname,
                'contrasena' => $contrasena,
                'ci' => $ci,
                'exp_ci' => $exp_ci,
                'username' => $ci,
                'joindate' => $joindate,
                'about' => $about,
                'contact' => $contact,
                'fees' => $fees,
                'branch' => $branch,
                'balance' => $balance,
                'carrera' => $carrera,
                'curso' => $curso, 
                'turno' => $turno,
                'modalidad' => $modalidad,
                'sucursal_varchar' => $sucursal_varchar
            ];

            $query = "INSERT INTO student (Cod_Estu, emailid, sname, contrasena, ci, exp_ci, username, joindate, about, contact, fees, branch, balance, carrera, curso, turno, modalidad, sucursal_varchar) 
                      VALUES (:Cod_Estu, :emailid, :sname, :contrasena, :ci, :exp_ci, :username, :joindate, :about, :contact, :fees, :branch, :balance, :carrera, :curso, :turno, :modalidad, :sucursal_varchar)";
            $stmt = $this->db->prepare($query);

            // Hashear la contraseña
            $datos['contrasena'] = password_hash($datos['contrasena'], PASSWORD_BCRYPT);

            foreach ($datos as $key => $value) {
                $stmt->bindValue(':' . $key, $value);
            }

            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error al agregar estudiante: " . $e->getMessage());
            echo "Error al agregar estudiante: " . $e->getMessage();
            return false;
        }
    }

    public function actualizarEstudiante($Cod_Estu, $ci, $emailid, $sname, $about, $contact, $fees, $branch, $balance, $carrera, $curso, $turno, $modalidad, $sucursal_varchar, $username, $delete_status)
    {
        try {
            $query = "UPDATE student 
                      SET ci = :ci, emailid = :emailid, sname = :sname, about = :about, contact = :contact, fees = :fees, branch = :branch, balance = :balance, carrera = :carrera, curso = :curso, turno = :turno, modalidad = :modalidad, sucursal_varchar = :sucursal_varchar, username = :username, delete_status = :delete_status 
                      WHERE Cod_Estu = :Cod_Estu";
            $stmt = $this->db->prepare($query);

            // Bind de los parámetros
            $stmt->bindParam(':Cod_Estu', $Cod_Estu);
            $stmt->bindParam(':ci', $ci);
            $stmt->bindParam(':emailid', $emailid);
            $stmt->bindParam(':sname', $sname);
            $stmt->bindParam(':about', $about);
            $stmt->bindParam(':contact', $contact);
            $stmt->bindParam(':fees', $fees);
            $stmt->bindParam(':branch', $branch);
            $stmt->bindParam(':balance', $balance);
            $stmt->bindParam(':carrera', $carrera);
            $stmt->bindParam(':curso', $curso);
            $stmt->bindParam(':turno', $turno);
            $stmt->bindParam(':modalidad', $modalidad);
            $stmt->bindParam(':sucursal_varchar', $sucursal_varchar);
            $stmt->bindParam(':username', $username);
            $stmt->bindParam(':delete_status', $delete_status);

            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error al actualizar estudiante: " . $e->getMessage());
            echo "Error al actualizar estudiante: " . $e->getMessage();
            return false;
        }
    }

    public function obtenerEstudiantePorId($student_id)
    {
        try {
            $query = "SELECT idRegistro AS id, sname AS nombre FROM student WHERE idRegistro = :student_id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':student_id', $student_id);
            $stmt->execute();
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al obtener estudiante por ID: " . $e->getMessage());
            return null;
        }
    }

    public function buscarEstudiantePorCI($ci)
{
    try {
        $query = "SELECT * FROM student WHERE ci = :ci LIMIT 1";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':ci', $ci, PDO::PARAM_STR);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC); // Retorna un solo estudiante
    } catch (PDOException $e) {
        error_log("Error al buscar estudiante por CI: " . $e->getMessage());
        return null;
    }
}


    public function obtenerCiPorId($id)
    {
        try {
            $query = "SELECT ci FROM student WHERE idRegistro = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return $result ? $result['ci'] : false;
        } catch (PDOException $e) {
            error_log("Error al obtener CI por ID: " . $e->getMessage());
            return false;
        }
    }

    public function listarTurnos()
    {
        try {
            $query = "SELECT * FROM turnos WHERE estado = 1";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al listar turnos: " . $e->getMessage());
            return [];
        }
    }

    public function listarCarreras()
    {
        try {
            $query = "SELECT * FROM carrera WHERE estado = 1";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al listar carreras: " . $e->getMessage());
            return [];
        }
    }

    public function listarCursos()
    {
        try {
            $query = "SELECT * FROM cursos WHERE estado = 1";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al listar cursos: " . $e->getMessage());
            return [];
        }
    }

    public function listarModalidades()
    {
        try {
            $query = "SELECT * FROM modalidad WHERE estado = 1";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al listar modalidades: " . $e->getMessage());
            return [];
        }
    }

    public function listarBranches()
    {
        try {
            $query = "SELECT * FROM branch WHERE delete_status = '0'";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al listar branches: " . $e->getMessage());
            return [];
        }
    }

    public function actualizarBalance($id, $nuevo_balance)
    {
        try {
            $query = "UPDATE student SET balance = :balance WHERE idRegistro = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':balance', $nuevo_balance);
            $stmt->bindParam(':id', $id);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error al actualizar balance: " . $e->getMessage());
            return false;
        }
    }

    public function registrarPago($id, $monto_pagado, $detalle)
    {
        try {
            $query = "INSERT INTO pagos (id_estudiante, monto, detalle) VALUES (:id_estudiante, :monto, :detalle)";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id_estudiante', $id);
            $stmt->bindParam(':monto', $monto_pagado);
            $stmt->bindParam(':detalle', $detalle);
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Error al registrar pago: " . $e->getMessage());
            return false;
        }
    }

    public function listarEstudiantesPorCarrera($carrera_id)
    {
        try {
            $query = "SELECT idRegistro, sname FROM student WHERE carrera = :carrera_id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':carrera_id', $carrera_id);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error al listar estudiantes por carrera: " . $e->getMessage());
            return [];
        }
    }
}
?>
