<?php
require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = getInput();

try {
    $db = getDB();

    switch ($method) {
        case 'GET':
            // Get all students or single student
            if (isset($_GET['id'])) {
                $stmt = $db->prepare("SELECT * FROM students WHERE id = ?");
                $stmt->execute([$_GET['id']]);
                sendJson($stmt->fetch());
            } else {
                $search = $_GET['search'] ?? '';
                $batch = $_GET['batch'] ?? '';
                $status = $_GET['status'] ?? '';

                $sql = "SELECT * FROM students WHERE is_active = 1";
                $params = [];

                if ($search) {
                    $sql .= " AND (full_name LIKE ? OR student_id LIKE ?)";
                    $params[] = "%$search%";
                    $params[] = "%$search%";
                }
                if ($batch) {
                    $sql .= " AND batch_name = ?";
                    $params[] = $batch;
                }
                if ($status) {
                    $sql .= " AND fee_status = ?";
                    $params[] = $status;
                }

                $sql .= " ORDER BY created_at DESC";
                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                sendJson($stmt->fetchAll());
            }
            break;

        case 'POST':
            // Add new student
            $studentId = 'SK' . str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT);
            $password = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 8);

            $stmt = $db->prepare("INSERT INTO students
                (student_id, full_name, date_of_birth, gender, phone, email,
                 guardian_name, guardian_phone, guardian_relationship,
                 batch_id, batch_name, skill_level, monthly_fee, joining_date, fee_status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')");

            $stmt->execute([
                $studentId,
                $input['fullName'] ?? '',
                $input['dateOfBirth'] ?? null,
                $input['gender'] ?? 'male',
                $input['phone'] ?? '',
                $input['email'] ?? '',
                $input['guardianName'] ?? '',
                $input['guardianPhone'] ?? '',
                $input['guardianRelationship'] ?? 'parent',
                $input['batchId'] ?? 1,
                $input['batchName'] ?? 'Morning Batch A',
                $input['skillLevel'] ?? 'beginner',
                $input['monthlyFee'] ?? 1500,
                $input['joiningDate'] ?? date('Y-m-d')
            ]);

            // Create student login
            $userStmt = $db->prepare("INSERT INTO users (username, password_hash, name, role, phone) VALUES (?, ?, ?, 'student', ?)");
            $userStmt->execute([$studentId, password_hash($password, PASSWORD_DEFAULT), $input['fullName'] ?? '', $input['phone'] ?? '']);

            sendJson([
                'success' => true,
                'studentId' => $studentId,
                'password' => $password,
                'id' => $db->lastInsertId()
            ]);
            break;

        case 'PUT':
            // Update student
            $id = $input['id'] ?? $_GET['id'] ?? 0;
            $stmt = $db->prepare("UPDATE students SET
                full_name = ?, phone = ?, guardian_name = ?, guardian_phone = ?,
                batch_id = ?, batch_name = ?, skill_level = ?, monthly_fee = ?,
                fee_status = ?, is_active = ?
                WHERE id = ?");
            $stmt->execute([
                $input['fullName'] ?? '',
                $input['phone'] ?? '',
                $input['guardianName'] ?? '',
                $input['guardianPhone'] ?? '',
                $input['batchId'] ?? 1,
                $input['batchName'] ?? '',
                $input['skillLevel'] ?? 'beginner',
                $input['monthlyFee'] ?? 1500,
                $input['feeStatus'] ?? 'pending',
                $input['isActive'] ?? 1,
                $id
            ]);
            sendJson(['success' => true]);
            break;

        case 'DELETE':
            // Soft delete student
            $id = $_GET['id'] ?? 0;
            $stmt = $db->prepare("UPDATE students SET is_active = 0 WHERE id = ?");
            $stmt->execute([$id]);
            sendJson(['success' => true]);
            break;

        default:
            sendJson(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    sendJson(['error' => $e->getMessage()], 500);
}
