<?php
/**
 * Mobile App API - Enhanced Endpoints
 * Provides REST API for mobile application
 */

require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Get request data
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'login':
            handleLogin($pdo, $input);
            break;
            
        case 'get_student_profile':
            authenticate($pdo);
            getStudentProfile($pdo, $_GET['student_id'] ?? null);
            break;
            
        case 'get_attendance':
            authenticate($pdo);
            getAttendance($pdo, $_GET['student_id'] ?? null, $_GET['month'] ?? null);
            break;
            
        case 'get_results':
            authenticate($pdo);
            getResults($pdo, $_GET['student_id'] ?? null, $_GET['exam_id'] ?? null);
            break;
            
        case 'get_fees':
            authenticate($pdo);
            getFees($pdo, $_GET['student_id'] ?? null);
            break;
            
        case 'get_timetable':
            authenticate($pdo);
            getTimetable($pdo, $_GET['class_id'] ?? null);
            break;
            
        case 'get_homework':
            authenticate($pdo);
            getHomework($pdo, $_GET['student_id'] ?? null, $_GET['date'] ?? null);
            break;
            
        case 'get_notices':
            authenticate($pdo);
            getNotices($pdo, $_GET['class_id'] ?? null, $_GET['limit'] ?? 10);
            break;
            
        case 'mark_attendance':
            authenticate($pdo);
            if ($method === 'POST') {
                markAttendance($pdo, $input);
            }
            break;
            
        case 'get_courses':
            authenticate($pdo);
            getCourses($pdo, $_GET['student_id'] ?? null);
            break;
            
        case 'get_live_classes':
            authenticate($pdo);
            getLiveClasses($pdo, $_GET['student_id'] ?? null, $_GET['date'] ?? date('Y-m-d'));
            break;
            
        case 'get_bus_info':
            authenticate($pdo);
            getBusInfo($pdo, $_GET['student_id'] ?? null);
            break;
            
        case 'get_hostel_info':
            authenticate($pdo);
            getHostelInfo($pdo, $_GET['student_id'] ?? null);
            break;
            
        case 'parent_login':
            handleParentLogin($pdo, $input);
            break;
            
        case 'get_parent_children':
            authenticate($pdo);
            getParentChildren($pdo, $_GET['parent_id'] ?? null);
            break;
            
        case 'parent_notifications':
            authenticate($pdo);
            getParentNotifications($pdo, $_GET['parent_id'] ?? null);
            break;
            
        case 'pay_fee_online':
            authenticate($pdo);
            if ($method === 'POST') {
                initiateFeePayment($pdo, $input);
            }
            break;
            
        case 'verify_payment':
            authenticate($pdo);
            verifyPayment($pdo, $input);
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['status' => 'error', 'message' => 'Unknown action']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

// Helper Functions
function authenticate($pdo) {
    $headers = getallheaders();
    $token = $headers['Authorization'] ?? '';
    
    if (empty($token)) {
        http_response_code(401);
        echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
        exit;
    }
    
    // Verify JWT token (simplified - implement proper JWT verification)
    // For now, we'll just check session
    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['status' => 'error', 'message' => 'Session expired']);
        exit;
    }
}

function handleLogin($pdo, $input) {
    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';
    
    $stmt = $pdo->prepare("
        SELECT u.*, s.id as student_id, s.first_name, s.last_name, s.class_id, c.name as class_name
        FROM users u
        LEFT JOIN students s ON u.id = s.user_id
        LEFT JOIN classes c ON s.class_id = c.id
        WHERE u.username = ? AND (u.role = 'student' OR u.role = 'parent')
    ");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        // Generate JWT token (simplified)
        $token = bin2hex(random_bytes(32));
        
        // Log login
        $pdo->prepare("
            INSERT INTO login_attempts (username, ip_address, user_agent, attempt_status)
            VALUES (?, ?, 'Mobile App', 'success')
        ")->execute([$username, $_SERVER['REMOTE_ADDR']]);
        
        echo json_encode([
            'status' => 'success',
            'data' => [
                'token' => $token,
                'user_id' => $user['id'],
                'role' => $user['role'],
                'student_id' => $user['student_id'],
                'name' => $user['first_name'] . ' ' . $user['last_name'],
                'class' => $user['class_name'],
                'photo' => $user['photo'] ?? null
            ]
        ]);
    } else {
        http_response_code(401);
        echo json_encode(['status' => 'error', 'message' => 'Invalid credentials']);
    }
}

function getStudentProfile($pdo, $studentId) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section,
               GROUP_CONCAT(DISTINCT sub.name) as subjects
        FROM students s
        LEFT JOIN classes c ON s.class_id = c.id
        LEFT JOIN student_subjects ss ON s.id = ss.student_id
        LEFT JOIN subjects sub ON ss.subject_id = sub.id
        WHERE s.id = ?
        GROUP BY s.id
    ");
    $stmt->execute([$studentId]);
    $student = $stmt->fetch();
    
    if ($student) {
        echo json_encode(['status' => 'success', 'data' => $student]);
    } else {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Student not found']);
    }
}

function getAttendance($pdo, $studentId, $month = null) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    if ($month) {
        $stmt = $pdo->prepare("
            SELECT date, status, remarks
            FROM attendance
            WHERE student_id = ? AND DATE_FORMAT(date, '%Y-%m') = ?
            ORDER BY date DESC
        ");
        $stmt->execute([$studentId, $month]);
    } else {
        $stmt = $pdo->prepare("
            SELECT date, status, remarks
            FROM attendance
            WHERE student_id = ? AND date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
            ORDER BY date DESC
        ");
        $stmt->execute([$studentId]);
    }
    
    $attendance = $stmt->fetchAll();
    
    // Calculate statistics
    $total = count($attendance);
    $present = count(array_filter($attendance, fn($a) => $a['status'] === 'present'));
    $absent = count(array_filter($attendance, fn($a) => $a['status'] === 'absent'));
    $late = count(array_filter($attendance, fn($a) => $a['status'] === 'late'));
    
    echo json_encode([
        'status' => 'success',
        'data' => [
            'attendance' => $attendance,
            'statistics' => [
                'total' => $total,
                'present' => $present,
                'absent' => $absent,
                'late' => $late,
                'percentage' => $total > 0 ? round(($present / $total) * 100, 2) : 0
            ]
        ]
    ]);
}

function getResults($pdo, $studentId, $examId = null) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    if ($examId) {
        $stmt = $pdo->prepare("
            SELECT r.*, e.name as exam_name, s.name as subject_name, s.code as subject_code
            FROM results r
            JOIN exams e ON r.exam_id = e.id
            JOIN subjects s ON r.subject_id = s.id
            WHERE r.student_id = ? AND r.exam_id = ?
        ");
        $stmt->execute([$studentId, $examId]);
    } else {
        $stmt = $pdo->prepare("
            SELECT r.*, e.name as exam_name, s.name as subject_name, s.code as subject_code
            FROM results r
            JOIN exams e ON r.exam_id = e.id
            JOIN subjects s ON r.subject_id = s.id
            WHERE r.student_id = ?
            ORDER BY r.created_at DESC
            LIMIT 50
        ");
        $stmt->execute([$studentId]);
    }
    
    $results = $stmt->fetchAll();
    echo json_encode(['status' => 'success', 'data' => $results]);
}

function getFees($pdo, $studentId) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT f.*, (f.amount - f.paid_amount) as due_amount
        FROM fees f
        WHERE f.student_id = ?
        ORDER BY f.due_date DESC
    ");
    $stmt->execute([$studentId]);
    $fees = $stmt->fetchAll();
    
    // Calculate totals
    $totalDue = array_sum(array_column($fees, 'due_amount'));
    $totalPaid = array_sum(array_column($fees, 'paid_amount'));
    $overdue = count(array_filter($fees, fn($f) => $f['status'] === 'overdue'));
    
    echo json_encode([
        'status' => 'success',
        'data' => [
            'fees' => $fees,
            'summary' => [
                'total_due' => $totalDue,
                'total_paid' => $totalPaid,
                'overdue_count' => $overdue
            ]
        ]
    ]);
}

function getTimetable($pdo, $classId) {
    if (!$classId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Class ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT t.*, s.name as subject_name, s.code as subject_code,
               CONCAT(te.first_name, ' ', te.last_name) as teacher_name
        FROM timetable t
        LEFT JOIN subjects s ON t.subject_id = s.id
        LEFT JOIN teachers te ON t.teacher_id = te.id
        WHERE t.class_id = ?
        ORDER BY t.day_of_week, t.start_time
    ");
    $stmt->execute([$classId]);
    $timetable = $stmt->fetchAll();
    
    // Group by day
    $grouped = [];
    foreach ($timetable as $item) {
        $day = $item['day_of_week'];
        if (!isset($grouped[$day])) {
            $grouped[$day] = [];
        }
        $grouped[$day][] = $item;
    }
    
    echo json_encode(['status' => 'success', 'data' => $grouped]);
}

function getHomework($pdo, $studentId, $date = null) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    if ($date) {
        $stmt = $pdo->prepare("
            SELECT a.*, c.course_name, s.name as subject_name,
                   sub.submitted_at, sub.status as submission_status
            FROM lms_assignments a
            JOIN courses c ON a.course_id = c.id
            LEFT JOIN subjects s ON c.subject_id = s.id
            LEFT JOIN assignment_submissions sub ON a.id = sub.assignment_id AND sub.student_id = ?
            WHERE c.class_id = (SELECT class_id FROM students WHERE id = ?)
            AND DATE(a.due_date) = ?
            AND a.status = 'published'
        ");
        $stmt->execute([$studentId, $studentId, $date]);
    } else {
        $stmt = $pdo->prepare("
            SELECT a.*, c.course_name, s.name as subject_name,
                   sub.submitted_at, sub.status as submission_status
            FROM lms_assignments a
            JOIN courses c ON a.course_id = c.id
            LEFT JOIN subjects s ON c.subject_id = s.id
            LEFT JOIN assignment_submissions sub ON a.id = sub.assignment_id AND sub.student_id = ?
            WHERE c.class_id = (SELECT class_id FROM students WHERE id = ?)
            AND a.due_date >= CURDATE()
            AND a.status = 'published'
            ORDER BY a.due_date
        ");
        $stmt->execute([$studentId, $studentId]);
    }
    
    $homework = $stmt->fetchAll();
    echo json_encode(['status' => 'success', 'data' => $homework]);
}

function getNotices($pdo, $classId = null, $limit = 10) {
    if ($classId) {
        $stmt = $pdo->prepare("
            SELECT n.*, u.username as created_by_name
            FROM notices n
            LEFT JOIN users u ON n.created_by = u.id
            WHERE n.target_class_id = ? OR n.target_class_id IS NULL
            AND n.status = 'published'
            ORDER BY n.created_at DESC
            LIMIT ?
        ");
        $stmt->execute([$classId, $limit]);
    } else {
        $stmt = $pdo->prepare("
            SELECT n.*, u.username as created_by_name
            FROM notices n
            LEFT JOIN users u ON n.created_by = u.id
            WHERE n.status = 'published'
            ORDER BY n.created_at DESC
            LIMIT ?
        ");
        $stmt->execute([$limit]);
    }
    
    $notices = $stmt->fetchAll();
    echo json_encode(['status' => 'success', 'data' => $notices]);
}

function getCourses($pdo, $studentId) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT c.*, CONCAT(t.first_name, ' ', t.last_name) as teacher_name,
               s.name as subject_name, e.progress_percent
        FROM courses c
        LEFT JOIN teachers t ON c.teacher_id = t.id
        LEFT JOIN subjects s ON c.subject_id = s.id
        LEFT JOIN student_enrollments e ON c.id = e.course_id AND e.student_id = ?
        WHERE c.class_id = (SELECT class_id FROM students WHERE id = ?)
        AND c.status = 'active'
    ");
    $stmt->execute([$studentId, $studentId]);
    $courses = $stmt->fetchAll();
    
    echo json_encode(['status' => 'success', 'data' => $courses]);
}

function getLiveClasses($pdo, $studentId, $date) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT lc.*, CONCAT(t.first_name, ' ', t.last_name) as teacher_name,
               s.name as subject_name
        FROM live_classes lc
        LEFT JOIN teachers t ON lc.teacher_id = t.id
        LEFT JOIN subjects s ON lc.subject_id = s.id
        WHERE lc.class_id = (SELECT class_id FROM students WHERE id = ?)
        AND DATE(lc.scheduled_at) = ?
        AND lc.status IN ('scheduled', 'ongoing')
        ORDER BY lc.scheduled_at
    ");
    $stmt->execute([$studentId, $date]);
    $classes = $stmt->fetchAll();
    
    echo json_encode(['status' => 'success', 'data' => $classes]);
}

function getBusInfo($pdo, $studentId) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT sbs.*, b.bus_number, b.bus_name, b.driver_name, b.driver_phone,
               r.route_name, r.start_point, r.end_point, r.fare_amount,
               rs1.stop_name as pickup_stop, rs2.stop_name as drop_stop
        FROM student_bus_subscriptions sbs
        JOIN buses b ON sbs.bus_id = b.id
        JOIN bus_routes r ON sbs.route_id = r.id
        LEFT JOIN bus_route_stops rs1 ON sbs.pickup_stop_id = rs1.id
        LEFT JOIN bus_route_stops rs2 ON sbs.drop_stop_id = rs2.id
        WHERE sbs.student_id = ? AND sbs.status = 'active'
    ");
    $stmt->execute([$studentId]);
    $busInfo = $stmt->fetch();
    
    if ($busInfo) {
        echo json_encode(['status' => 'success', 'data' => $busInfo]);
    } else {
        echo json_encode(['status' => 'success', 'data' => null, 'message' => 'No active bus subscription']);
    }
}

function getHostelInfo($pdo, $studentId) {
    if (!$studentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Student ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT ha.*, hr.room_number, hr.room_type, hr.amenities, hr.monthly_rent,
               hb.building_name, hb.warden_name, hb.warden_phone
        FROM hostel_allocations ha
        JOIN hostel_rooms hr ON ha.room_id = hr.id
        JOIN hostel_buildings hb ON hr.building_id = hb.id
        WHERE ha.student_id = ? AND ha.status = 'active'
    ");
    $stmt->execute([$studentId]);
    $hostelInfo = $stmt->fetch();
    
    if ($hostelInfo) {
        echo json_encode(['status' => 'success', 'data' => $hostelInfo]);
    } else {
        echo json_encode(['status' => 'success', 'data' => null, 'message' => 'No active hostel allocation']);
    }
}

function handleParentLogin($pdo, $input) {
    $username = $input['username'] ?? '';
    $password = $input['password'] ?? '';
    
    $stmt = $pdo->prepare("
        SELECT u.*, p.id as parent_id, p.father_name, p.mother_name
        FROM users u
        JOIN parents p ON u.id = p.user_id
        WHERE u.username = ? AND u.role = 'parent'
    ");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        $token = bin2hex(random_bytes(32));
        
        echo json_encode([
            'status' => 'success',
            'data' => [
                'token' => $token,
                'parent_id' => $user['parent_id'],
                'name' => $user['father_name'],
                'email' => $user['email']
            ]
        ]);
    } else {
        http_response_code(401);
        echo json_encode(['status' => 'error', 'message' => 'Invalid credentials']);
    }
}

function getParentChildren($pdo, $parentId) {
    if (!$parentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Parent ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, ps.relation
        FROM students s
        JOIN parent_students ps ON s.id = ps.student_id
        LEFT JOIN classes c ON s.class_id = c.id
        WHERE ps.parent_id = ? AND s.status = 'active'
    ");
    $stmt->execute([$parentId]);
    $children = $stmt->fetchAll();
    
    echo json_encode(['status' => 'success', 'data' => $children]);
}

function getParentNotifications($pdo, $parentId) {
    if (!$parentId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Parent ID required']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT * FROM parent_notifications
        WHERE parent_id = ?
        ORDER BY sent_at DESC
        LIMIT 50
    ");
    $stmt->execute([$parentId]);
    $notifications = $stmt->fetchAll();
    
    // Count unread
    $unread = count(array_filter($notifications, fn($n) => !$n['is_read']));
    
    echo json_encode([
        'status' => 'success',
        'data' => [
            'notifications' => $notifications,
            'unread_count' => $unread
        ]
    ]);
}

function initiateFeePayment($pdo, $input) {
    $studentId = $input['student_id'] ?? null;
    $feeId = $input['fee_id'] ?? null;
    $amount = $input['amount'] ?? 0;
    $paymentMethod = $input['payment_method'] ?? 'online';
    
    if (!$studentId || !$feeId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
        return;
    }
    
    // Generate transaction ID
    $transactionId = 'FEE' . date('Ymd') . strtoupper(substr(uniqid(), -6));
    
    // Create payment record
    $stmt = $pdo->prepare("
        INSERT INTO fee_payments (fee_id, amount, payment_method, transaction_id, payment_date, received_by)
        VALUES (?, ?, ?, ?, CURDATE(), NULL)
    ");
    $stmt->execute([$feeId, $amount, $paymentMethod, $transactionId]);
    
    echo json_encode([
        'status' => 'success',
        'data' => [
            'transaction_id' => $transactionId,
            'payment_url' => BASE_URL . '/fees/pay_online.php?tx=' . $transactionId,
            'amount' => $amount
        ]
    ]);
}

function verifyPayment($pdo, $input) {
    $transactionId = $input['transaction_id'] ?? '';
    
    $stmt = $pdo->prepare("
        SELECT * FROM fee_payments WHERE transaction_id = ?
    ");
    $stmt->execute([$transactionId]);
    $payment = $stmt->fetch();
    
    if ($payment) {
        echo json_encode([
            'status' => 'success',
            'data' => [
                'transaction_id' => $payment['transaction_id'],
                'amount' => $payment['amount'],
                'status' => $payment['payment_method'],
                'date' => $payment['payment_date']
            ]
        ]);
    } else {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Payment not found']);
    }
}

function markAttendance($pdo, $input) {
    $studentId = $input['student_id'] ?? null;
    $date = $input['date'] ?? date('Y-m-d');
    $status = $input['status'] ?? 'present';
    $busId = $input['bus_id'] ?? null;
    $shift = $input['shift'] ?? 'morning';
    
    if (!$studentId || !$busId) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
        return;
    }
    
    // Check if record exists
    $stmt = $pdo->prepare("
        SELECT id FROM bus_attendance 
        WHERE student_id = ? AND date = ? AND bus_id = ?
    ");
    $stmt->execute([$studentId, $date, $busId]);
    $existing = $stmt->fetch();
    
    if ($existing) {
        // Update
        $field = $shift === 'morning' ? 'morning_pickup' : 'evening_drop';
        $stmt = $pdo->prepare("
            UPDATE bus_attendance SET $field = 1, marked_by = ?
            WHERE id = ?
        ");
        $stmt->execute([$_SESSION['user_id'] ?? null, $existing['id']]);
    } else {
        // Insert
        $stmt = $pdo->prepare("
            INSERT INTO bus_attendance (student_id, bus_id, route_id, date, morning_pickup, marked_by)
            SELECT student_id, bus_id, route_id, ?, 1, ?
            FROM student_bus_subscriptions
            WHERE student_id = ? AND bus_id = ? AND status = 'active'
        ");
        $stmt->execute([$date, $_SESSION['user_id'] ?? null, $studentId, $busId]);
    }
    
    echo json_encode(['status' => 'success', 'message' => 'Attendance marked']);
}
