<?php
class exam_enrollments_model {
    private $db;
    public function __construct() {
        $this->db = database::connect();
    }

    public function getAll() {
        return $this->db->query("SELECT * FROM exam_enrollments")->fetchAll(PDO::FETCH_ASSOC);
    }

    public function get($ref) {
        $stmt = $this->db->prepare("SELECT * FROM students JOIN exam_enrollments ON students.id
          = exam_enrollments.student_id JOIN payments ON exam_enrollments.reference_no = payments.reference_no WHERE exam_enrollments.reference_no = ?");
        $stmt->execute([$ref]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function get_v2($id) {
        $stmt = $this->db->prepare("SELECT * FROM students JOIN exam_enrollments ON students.id
          = exam_enrollments.student_id JOIN payments ON exam_enrollments.reference_no = payments.reference_no WHERE exam_enrollments.student_id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function get_dockets($id) {
        $stmt = $this->db->prepare("SELECT a.create_date, a.reference_no, CONCAT(b.first_name, ' ', b.last_name) as name FROM students b
          JOIN exam_enrollments a ON a.student_id = b.id WHERE b.student_number = ?");
        $stmt->execute([$id]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function insert($data) {
        $keys = implode(',', array_keys($data));
        $placeholders = implode(',', array_fill(0, count($data), '?'));
        $stmt = $this->db->prepare("INSERT INTO exam_enrollments ($keys) VALUES ($placeholders)");
        return $stmt->execute(array_values($data));
    }

    public function update($id, $data) {
        $fields = implode(',', array_map(fn($k) => "$k = ?", array_keys($data)));
        $stmt = $this->db->prepare("UPDATE exam_enrollments SET $fields WHERE id = ?");
        return $stmt->execute([...array_values($data), $id]);
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM exam_enrollments WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
?>
