CREATE DATABASE IF NOT EXISTS transfer_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE transfer_db;

-- หลักสูตร
CREATE TABLE curricula (
    id INT AUTO_INCREMENT PRIMARY KEY,
    code VARCHAR(10) NOT NULL UNIQUE,
    name_th VARCHAR(255) NOT NULL,
    name_en VARCHAR(255) NOT NULL,
    total_credits INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- กลุ่มวิชาในหลักสูตร (โครงสร้าง)
CREATE TABLE course_groups (
    id INT AUTO_INCREMENT PRIMARY KEY,
    curriculum_id INT NOT NULL,
    parent_id INT DEFAULT NULL,
    code VARCHAR(50) NOT NULL,
    name_th VARCHAR(255) NOT NULL,
    min_credits INT NOT NULL DEFAULT 0,
    sort_order INT NOT NULL DEFAULT 0,
    FOREIGN KEY (curriculum_id) REFERENCES curricula(id) ON DELETE CASCADE,
    FOREIGN KEY (parent_id) REFERENCES course_groups(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- รายวิชาในหลักสูตร
CREATE TABLE courses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    group_id INT NOT NULL,
    code VARCHAR(20) NOT NULL UNIQUE,
    name_th VARCHAR(255) NOT NULL,
    name_en VARCHAR(255) DEFAULT '',
    credits DECIMAL(3,1) NOT NULL,
    lecture_hours INT NOT NULL DEFAULT 0,
    practice_hours INT NOT NULL DEFAULT 0,
    self_study_hours INT NOT NULL DEFAULT 0,
    sort_order INT NOT NULL DEFAULT 0,
    FOREIGN KEY (group_id) REFERENCES course_groups(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- นักศึกษา
CREATE TABLE students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    student_code VARCHAR(20) NOT NULL UNIQUE,
    name_th VARCHAR(255) NOT NULL,
    name_en VARCHAR(255) DEFAULT '',
    faculty VARCHAR(255) DEFAULT '',
    graduated_institution VARCHAR(255) DEFAULT '',
    curriculum_id INT NOT NULL,
    enrollment_year INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (curriculum_id) REFERENCES curricula(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- รายวิชาที่นักศึกษาเรียนผ่านแล้ว (ทั้งเทียบโอนและลงทะเบียน)
CREATE TABLE student_courses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    student_id INT NOT NULL,
    course_id INT DEFAULT NULL,
    course_code VARCHAR(20) NOT NULL,
    course_name_th VARCHAR(255) NOT NULL,
    credits DECIMAL(3,1) NOT NULL,
    lecture_hours INT NOT NULL DEFAULT 0,
    practice_hours INT NOT NULL DEFAULT 0,
    self_study_hours INT NOT NULL DEFAULT 0,
    source_type ENUM('transfer','manual') NOT NULL DEFAULT 'manual',
    source_file VARCHAR(255) DEFAULT NULL,
    notes TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
    FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
