<?php
// ========================================================
// HISTORY AI - JSON Database Storage Driver (Không cần MySQL)
// Tự động tạo và lưu trữ dữ liệu vào các file .json
// ========================================================

// Headers CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Content-Type: application/json; charset=UTF-8');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Đường dẫn thư mục lưu trữ file JSON
define('DATA_DIR', __DIR__ . '/../data');

// Cấu hình AI Provider (Google Gemini API Key)
define('GEMINI_API_KEY', getenv('GEMINI_API_KEY') ?: '');

// Đảm bảo thư mục data luôn tồn tại
if (!file_exists(DATA_DIR)) {
    mkdir(DATA_DIR, 0777, true);
}

class JsonDB {
    private static function getFilePath($table) {
        return DATA_DIR . '/' . $table . '.json';
    }

    // Đọc toàn bộ bảng JSON
    public static function read($table) {
        $file = self::getFilePath($table);
        if (!file_exists($file)) {
            // Khởi tạo bảng mẫu mặc định nếu chưa có
            self::initDefaultData($table);
        }
        $content = file_get_contents($file);
        return json_decode($content, true) ?: [];
    }

    // Ghi toàn bộ dữ liệu vào bảng JSON
    public static function write($table, $data) {
        $file = self::getFilePath($table);
        return file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
    }

    // Tìm một bản ghi theo điều kiện callback
    public static function findOne($table, $callback) {
        $items = self::read($table);
        foreach ($items as $item) {
            if ($callback($item)) {
                return $item;
            }
        }
        return null;
    }

    // Tìm danh sách bản ghi theo điều kiện
    public static function find($table, $callback = null) {
        $items = self::read($table);
        if ($callback === null) return $items;
        return array_values(array_filter($items, $callback));
    }

    // Thêm bản ghi mới (tự tăng id)
    public static function insert($table, $record) {
        $items = self::read($table);
        $maxId = 0;
        foreach ($items as $item) {
            if (isset($item['id']) && $item['id'] > $maxId) {
                $maxId = $item['id'];
            }
        }
        $record['id'] = $maxId + 1;
        $record['created_at'] = date('Y-m-d H:i:s');
        $items[] = $record;
        self::write($table, $items);
        return $record;
    }

    // Cập nhật bản ghi theo ID
    public static function update($table, $id, $updateData) {
        $items = self::read($table);
        $found = false;
        foreach ($items as &$item) {
            if ($item['id'] == $id) {
                $item = array_merge($item, $updateData);
                $item['updated_at'] = date('Y-m-d H:i:s');
                $found = true;
                break;
            }
        }
        if ($found) {
            self::write($table, $items);
            return true;
        }
        return false;
    }

    // Dữ liệu mẫu ban đầu
    private static function initDefaultData($table) {
        $defaults = [];
        if ($table === 'users') {
            $defaults = [
                [
                    'id' => 1,
                    'fullname' => 'Cô Nguyễn Thị Lịch Sử',
                    'email' => 'giaovien@historyai.edu.vn',
                    // Mật khẩu: 123456
                    'password' => '$2y$10$wT0o3qG3Kk0lH2k5rK5gG.OcbY9Y.X5c8C/kL4vFwY3d2j6.5A.yK',
                    'role' => 'teacher',
                    'school' => 'THPT Chuyên',
                    'grade' => '12',
                    'token' => 'teacher_demo_token_123',
                    'created_at' => date('Y-m-d H:i:s')
                ],
                [
                    'id' => 2,
                    'fullname' => 'Trần Văn An',
                    'email' => 'hocsinh@historyai.edu.vn',
                    // Mật khẩu: 123456
                    'password' => '$2y$10$wT0o3qG3Kk0lH2k5rK5gG.OcbY9Y.X5c8C/kL4vFwY3d2j6.5A.yK',
                    'role' => 'student',
                    'school' => 'THPT Chuyên',
                    'grade' => '12',
                    'token' => 'student_demo_token_123',
                    'created_at' => date('Y-m-d H:i:s')
                ]
            ];
        } elseif ($table === 'classes') {
            $defaults = [
                [
                    'id' => 1,
                    'name' => 'Lịch sử 12A1',
                    'grade' => '12',
                    'code' => 'LS12A1',
                    'teacher_id' => 1,
                    'description' => 'Lớp học bồi dưỡng Lịch sử Việt Nam hiện đại',
                    'created_at' => date('Y-m-d H:i:s')
                ]
            ];
        } elseif ($table === 'class_members') {
            $defaults = [
                [
                    'id' => 1,
                    'class_id' => 1,
                    'student_id' => 2,
                    'joined_at' => date('Y-m-d H:i:s')
                ]
            ];
        } elseif ($table === 'assignments') {
            $defaults = [
                [
                    'id' => 1,
                    'title' => 'Kiểm tra 15 phút: Cách mạng tháng Tám 1945',
                    'description' => 'Đề kiểm tra kiến thức giai đoạn chuẩn bị và Tổng khởi nghĩa tháng Tám năm 1945.',
                    'class_id' => 1,
                    'teacher_id' => 1,
                    'time_limit' => 15,
                    'total_points' => 10,
                    'status' => 'published',
                    'created_at' => date('Y-m-d H:i:s')
                ]
            ];
        } elseif ($table === 'questions') {
            $defaults = [
                [
                    'id' => 1,
                    'assignment_id' => 1,
                    'type' => 'multiple_choice',
                    'content' => 'Chiến thắng nào của quân và dân ta đã kết thúc hoàn toàn cuộc kháng chiến chống thực dân Pháp (1945 - 1954)?',
                    'options' => [
                        'A' => 'Chiến thắng Việt Bắc thu - đông 1947',
                        'B' => 'Chiến thắng Biên giới thu - đông 1950',
                        'C' => 'Chiến thắng Điện Biên Phủ 1954',
                        'D' => 'Chiến dịch Tây Bắc 1952'
                    ],
                    'correct_answer' => 'C',
                    'points' => 2.5,
                    'explanation' => 'Chiến thắng lịch sử Điện Biên Phủ ngày 7/5/1954 đã đập tan tập đoàn cứ điểm mạnh nhất Đông Dương của Pháp.',
                    'created_at' => date('Y-m-d H:i:s')
                ],
                [
                    'id' => 2,
                    'assignment_id' => 1,
                    'type' => 'multiple_choice',
                    'content' => 'Mặt trận Việt Minh (Việt Nam Độc lập Đồng minh) được thành lập vào năm nào?',
                    'options' => [
                        'A' => '1930',
                        'B' => '1941',
                        'C' => '1945',
                        'D' => '1946'
                    ],
                    'correct_answer' => 'B',
                    'points' => 2.5,
                    'explanation' => 'Mặt trận Việt Minh được thành lập ngày 19/5/1941 tại Pác Bó (Cao Bằng).',
                    'created_at' => date('Y-m-d H:i:s')
                ],
                [
                    'id' => 3,
                    'assignment_id' => 1,
                    'type' => 'short_answer',
                    'content' => 'Chủ tịch Hồ Chí Minh đọc bản Tuyên ngôn Độc lập khai sinh ra nước Việt Nam Dân chủ Cộng hòa vào ngày tháng năm nào? (Định dạng: ngày/tháng/năm)',
                    'options' => null,
                    'correct_answer' => '02/09/1945',
                    'points' => 2.5,
                    'explanation' => 'Vào ngày 2 tháng 9 năm 1945 tại Quảng trường Ba Đình, Hà Nội.',
                    'created_at' => date('Y-m-d H:i:s')
                ],
                [
                    'id' => 4,
                    'assignment_id' => 1,
                    'type' => 'essay',
                    'content' => 'Hãy phân tích nguyên nhân thắng lợi và ý nghĩa lịch sử của Cách mạng tháng Tám năm 1945 đối với dân tộc Việt Nam.',
                    'options' => null,
                    'correct_answer' => 'Yêu cầu nêu rõ: Nguyên nhân chủ quan (Đảng lãnh đạo, khối đại đoàn kết, chuẩn bị 15 năm), nguyên nhân khách quan (quân Đồng minh tiêu diệt phát xít). Ý nghĩa: Lật đổ ách thống trị thực dân - phong kiến, lập nên nhà nước dân chủ công nông đầu tiên ở Đông Nam Á.',
                    'points' => 2.5,
                    'explanation' => 'Chấm theo mức độ đầy đủ của các luận điểm lịch sử.',
                    'created_at' => date('Y-m-d H:i:s')
                ]
            ];
        } elseif ($table === 'submissions') {
            $defaults = [];
        }

        self::write($table, $defaults);
    }
}

// Hàm chuẩn hóa response JSON
function sendResponse($success, $message, $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit();
}

// Lấy payload JSON từ request
function getJsonInput() {
    $raw = file_get_contents('php://input');
    return json_decode($raw, true) ?: [];
}

// Xác thực Token người dùng từ Header
function authenticateUser() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (empty($authHeader) || !preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
        sendResponse(false, 'Yêu cầu token xác thực!', null, 401);
    }
    
    $token = $matches[1];
    $user = JsonDB::findOne('users', function($u) use ($token) {
        return isset($u['token']) && $u['token'] === $token;
    });
    
    if (!$user) {
        sendResponse(false, 'Phiên đăng nhập không hợp lệ hoặc đã hết hạn!', null, 401);
    }
    
    return $user;
}
?>
