<?php
/**
 * Parent Registration Debug Version
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$error = '';
$success = '';
$debug_info = '';

// Debug: Check if form is being submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $debug_info .= "✅ Form submitted via POST<br>";
    $debug_info .= "POST data: " . print_r($_POST, true) . "<br>";
    
    // Simple validation without CSRF for now to avoid potential issues
    $username = trim($_POST['username'] ?? '');
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $father_name = trim($_POST['father_name'] ?? '');
    $father_phone = trim($_POST['father_phone'] ?? '');
    $mother_name = trim($_POST['mother_name'] ?? '');
    $mother_phone = trim($_POST['mother_phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $linked_student_ids = $_POST['linked_students'] ?? [];
    
    $debug_info .= "Username: " . htmlspecialchars($username) . "<br>";
    $debug_info .= "Email: " . htmlspecialchars($email) . "<br>";
    $debug_info .= "Father name: " . htmlspecialchars($father_name) . "<br>";
    $debug_info .= "Linked students: " . print_r($linked_student_ids, true) . "<br>";
    
    // Validation
    if (empty($username) || empty($email) || empty($password) || empty($father_name)) {
        $error = '❌ সবগুলো তারকা চিহ্নিত ফিল্ড পূরণ করুন!';
        $debug_info .= "❌ Validation failed: Required fields missing<br>";
    } elseif ($password !== $confirm_password) {
        $error = '❌ পাসওয়ার্ড এবং নিশ্চিতকরণ পাসওয়ার্ড মেলে না!';
        $debug_info .= "❌ Validation failed: Passwords don't match<br>";
    } elseif (strlen($password) < 6) {
        $error = '❌ পাসওয়ার্ড অন্তত ৬ অক্ষরের হতে হবে!';
        $debug_info .= "❌ Validation failed: Password too short<br>";
    } else {
        $debug_info .= "✅ Basic validation passed<br>";
        try {
            // Check if username already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $error = '❌ এই ইউজারনেমটি ইতিমধ্যে ব্যবহৃত হয়েছে!';
                $debug_info .= "❌ Username already exists<br>";
            } else {
                // Check if email already exists
                $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
                $stmt->execute([$email]);
                if ($stmt->fetch()) {
                    $error = '❌ এই ইমেইলটি ইতিমধ্যে ব্যবহৃত হয়েছে!';
                    $debug_info .= "❌ Email already exists<br>";
                } else {
                    $debug_info .= "✅ Username and email are unique<br>";
                    
                    // Begin transaction
                    $pdo->beginTransaction();
                    $debug_info .= "✅ Database transaction started<br>";
                    
                    // Create user account
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $debug_info .= "✅ Password hashed<br>";
                    
                    $stmt = $pdo->prepare("
                        INSERT INTO users (username, password, email, role, status) 
                        VALUES (?, ?, ?, 'parent', 'active')
                    ");
                    $stmt->execute([$username, $hashed_password, $email]);
                    $user_id = $pdo->lastInsertId();
                    $debug_info .= "✅ User created with ID: " . $user_id . "<br>";
                    
                    // Create parent profile
                    $stmt = $pdo->prepare("
                        INSERT INTO parents (user_id, father_name, father_phone, mother_name, mother_phone, address) 
                        VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$user_id, $father_name, $father_phone, $mother_name, $mother_phone, $address]);
                    $parent_id = $pdo->lastInsertId();
                    $debug_info .= "✅ Parent profile created with ID: " . $parent_id . "<br>";
                    
                    // Link parent to selected students
                    $linked_count = 0;
                    foreach ($linked_student_ids as $student_id) {
                        if (is_numeric($student_id)) {
                            // Check if student exists and is valid
                            $check_stmt = $pdo->prepare("SELECT id FROM students WHERE id = ?");
                            $check_stmt->execute([(int)$student_id]);
                            if ($check_stmt->fetch()) {
                                // Link parent to student
                                $link_stmt = $pdo->prepare("
                                    INSERT INTO parent_students (parent_id, student_id, relation, is_primary) 
                                    VALUES (?, ?, 'father', TRUE)
                                ");
                                $link_stmt->execute([$parent_id, (int)$student_id]);
                                $linked_count++;
                                $debug_info .= "✅ Linked to student ID: " . (int)$student_id . "<br>";
                            }
                        }
                    }
                    
                    $pdo->commit();
                    $debug_info .= "✅ Database transaction committed<br>";
                    
                    $success = '✅ অভিভাবক একাউন্ট সফলভাবে তৈরি হয়েছে! আপনি এখন লগইন করতে পারবেন।';
                    $debug_info .= "✅ Registration completed successfully<br>";
                    
                    // Clear form data
                    $username = $email = $father_name = $father_phone = $mother_name = $mother_phone = $address = '';
                    $linked_student_ids = [];
                }
            }
        } catch (Exception $e) {
            $pdo->rollback();
            $error = '❌ রেজিস্ট্রেশন ত্রুটি: ' . $e->getMessage();
            $debug_info .= "❌ Database error: " . $e->getMessage() . "<br>";
            $debug_info .= "❌ Stack trace: " . $e->getTraceAsString() . "<br>";
        }
    }
} else {
    $debug_info .= "📝 Form not submitted yet (GET request)<br>";
}

// Get list of students for selection
$students = [];
try {
    $stmt = $pdo->prepare("
        SELECT s.id, s.first_name, s.last_name, s.roll_number, c.name as class_name, s.session, s.group_name
        FROM students s
        LEFT JOIN classes c ON s.class_id = c.id
        WHERE s.status = 'active'
        ORDER BY c.name, s.roll_number
    ");
    $stmt->execute();
    $students = $stmt->fetchAll();
    $debug_info .= "✅ Found " . count($students) . " active students<br>";
} catch (Exception $e) {
    $error = 'তথ্য লোড করতে সমস্যা হয়েছে: ' . $e->getMessage();
    $debug_info .= "❌ Error loading students: " . $e->getMessage() . "<br>";
}

// Check required tables
try {
    $tables_to_check = ['users', 'parents', 'students', 'parent_students', 'classes'];
    foreach ($tables_to_check as $table) {
        $result = $pdo->query("SHOW TABLES LIKE '$table'");
        if ($result && $result->fetch()) {
            $debug_info .= "✅ Table '$table' exists<br>";
        } else {
            $debug_info .= "❌ Table '$table' does NOT exist<br>";
        }
    }
} catch (Exception $e) {
    $debug_info .= "❌ Error checking tables: " . $e->getMessage() . "<br>";
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অভিভাবক নিবন্ধন - Debug Version</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { background: #f8f9fa; }
        .debug-panel { background: #e9ecef; border: 1px solid #dee2e6; padding: 15px; margin: 15px 0; }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3 class="mb-0"><i class="fas fa-user-plus"></i> অভিভাবক নিবন্ধন (Debug)</h3>
                    </div>
                    <div class="card-body">
                        <!-- Debug Information -->
                        <div class="debug-panel">
                            <h5>🔧 Debug Information:</h5>
                            <?= $debug_info ?>
                        </div>
                        
                        <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?>
                        </div>
                        <?php endif; ?>
                        
                        <form method="POST" action="">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">ইউজারনেম <span class="text-danger">*</span></label>
                                    <input type="text" name="username" class="form-control" placeholder="ইউজারনেম" value="<?= htmlspecialchars($username ?? '') ?>" required>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">ইমেইল <span class="text-danger">*</span></label>
                                    <input type="email" name="email" class="form-control" placeholder="ইমেইল" value="<?= htmlspecialchars($email ?? '') ?>" required>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">পাসওয়ার্ড <span class="text-danger">*</span></label>
                                    <input type="password" name="password" class="form-control" placeholder="পাসওয়ার্ড" required>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">পাসওয়ার্ড নিশ্চিতকরণ <span class="text-danger">*</span></label>
                                    <input type="password" name="confirm_password" class="form-control" placeholder="পাসওয়ার্ড নিশ্চিতকরণ" required>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">বাবার নাম <span class="text-danger">*</span></label>
                                <input type="text" name="father_name" class="form-control" placeholder="বাবার নাম" value="<?= htmlspecialchars($father_name ?? '') ?>" required>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">বাবার ফোন নম্বর</label>
                                    <input type="text" name="father_phone" class="form-control" placeholder="বাবার ফোন নম্বর" value="<?= htmlspecialchars($father_phone ?? '') ?>">
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">মায়ের ফোন নম্বর</label>
                                    <input type="text" name="mother_phone" class="form-control" placeholder="মায়ের ফোন নম্বর" value="<?= htmlspecialchars($mother_phone ?? '') ?>">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">মায়ের নাম</label>
                                <input type="text" name="mother_name" class="form-control" placeholder="মায়ের নাম" value="<?= htmlspecialchars($mother_name ?? '') ?>">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">ঠিকানা</label>
                                <textarea name="address" class="form-control" placeholder="ঠিকানা" rows="3"><?= htmlspecialchars($address ?? '') ?></textarea>
                            </div>
                            
                            <!-- Student Selection -->
                            <div class="mb-4">
                                <label class="form-label">আপনার সন্তান (ছাত্র/ছাত্রী) নির্বাচন করুন:</label>
                                <div class="border rounded p-3" style="max-height: 200px; overflow-y: auto;">
                                    <?php if (count($students) > 0): ?>
                                        <?php foreach ($students as $student): ?>
                                            <div class="form-check mb-2">
                                                <input class="form-check-input" type="checkbox" name="linked_students[]" value="<?= $student['id'] ?>" id="student_<?= $student['id'] ?>">
                                                <label class="form-check-label" for="student_<?= $student['id'] ?>">
                                                    <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?> - 
                                                    ক্লাস: <?= htmlspecialchars($student['class_name']) ?>, 
                                                    রোল: <?= $student['roll_number'] ?>,
                                                    সেশন: <?= htmlspecialchars($student['session'] ?? 'N/A') ?>,
                                                    গ্রুপ: <?= htmlspecialchars($student['group_name'] ?? 'N/A') ?>
                                                </label>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <p class="text-muted">কোনো ছাত্র/ছাত্রী পাওয়া যায়নি।</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 mb-3">
                                <i class="fas fa-user-plus"></i> নিবন্ধন করুন
                            </button>
                            
                            <div class="text-center">
                                <a href="parent_login.php" class="btn btn-outline-secondary">লগইন পেজে ফিরে যান</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>