<?php
/**
 * Parent Registration - Fixed Version
 */

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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 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'] ?? [];
    
    // Validation
    if (empty($username) || empty($email) || empty($password) || empty($father_name)) {
        $error = '❌ সবগুলো তারকা চিহ্নিত ফিল্ড পূরণ করুন!';
    } elseif ($password !== $confirm_password) {
        $error = '❌ পাসওয়ার্ড এবং নিশ্চিতকরণ পাসওয়ার্ড মেলে না!';
    } elseif (strlen($password) < 6) {
        $error = '❌ পাসওয়ার্ড অন্তত ৬ অক্ষরের হতে হবে!';
    } else {
        try {
            // Check if username already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $error = '❌ এই ইউজারনেমটি ইতিমধ্যে ব্যবহৃত হয়েছে!';
            } else {
                // Check if email already exists
                $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
                $stmt->execute([$email]);
                if ($stmt->fetch()) {
                    $error = '❌ এই ইমেইলটি ইতিমধ্যে ব্যবহৃত হয়েছে!';
                } else {
                    // Begin transaction
                    $pdo->beginTransaction();
                    
                    // Create user account
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("
                        INSERT INTO users (username, password, email, role, status) 
                        VALUES (?, ?, ?, 'parent', 'active')
                    ");
                    $stmt->execute([$username, $hashed_password, $email]);
                    $user_id = $pdo->lastInsertId();
                    
                    // 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();
                    
                    // Link parent to selected students
                    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]);
                            }
                        }
                    }
                    
                    $pdo->commit();
                    
                    $success = '✅ অভিভাবক একাউন্ট সফলভাবে তৈরি হয়েছে! আপনি এখন লগইন করতে পারবেন।';
                    
                    // 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();
        }
    }
}

// Get list of students for selection (simple version without filters)
$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();
} catch (Exception $e) {
    $students = [];
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অভিভাবক নিবন্ধন - <?= APP_NAME ?></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">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* Apply Hind Siliguri font to all elements */
        * {
            font-family: 'Hind Siliguri', sans-serif !important;
        }
        
        /* Font Awesome Icons - Restore Original Font */
        .fas, .far, .fab, .fa,
        .fas::before, .far::before, .fab::before, .fa::before {
            font-family: 'Font Awesome 6 Free', 'Font Awesome 5 Free', 'FontAwesome' !important;
            font-weight: 900 !important;
        }
        
        .far::before {
            font-weight: 400 !important;
        }
        
        .fab::before {
            font-family: 'Font Awesome 6 Brands', 'Font Awesome 5 Brands', 'FontAwesome' !important;
        }
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .register-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .register-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .register-form {
            padding: 40px;
        }
        .form-control {
            border-radius: 10px;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .btn-register {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 12px;
            font-weight: 600;
        }
        .parent-icon {
            font-size: 60px;
            margin-bottom: 15px;
        }
        .student-checkbox {
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 5px;
            margin: 5px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="register-card">
                    <div class="register-header">
                        <i class="fas fa-user-plus parent-icon"></i>
                        <h3 class="mb-2">অভিভাবক নিবন্ধন</h3>
                        <p class="mb-0">আপনার সন্তানের তথ্য দেখতে একাউন্ট তৈরি করুন</p>
                    </div>
                    
                    <div class="register-form">
                        <?php if ($error): ?>
                        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                        <div class="alert alert-success"><?= 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>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-user"></i></span>
                                        <input type="text" name="username" class="form-control" placeholder="ইউজারনেম" value="<?= htmlspecialchars($username ?? '') ?>" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">ইমেইল <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                        <input type="email" name="email" class="form-control" placeholder="ইমেইল" value="<?= htmlspecialchars($email ?? '') ?>" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">পাসওয়ার্ড <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                        <input type="password" name="password" class="form-control" placeholder="পাসওয়ার্ড" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">পাসওয়ার্ড নিশ্চিতকরণ <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                        <input type="password" name="confirm_password" class="form-control" placeholder="পাসওয়ার্ড নিশ্চিতকরণ" required>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">বাবার নাম <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                                    <input type="text" name="father_name" class="form-control" placeholder="বাবার নাম" value="<?= htmlspecialchars($father_name ?? '') ?>" required>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">বাবার ফোন নম্বর</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-phone"></i></span>
                                        <input type="text" name="father_phone" class="form-control" placeholder="বাবার ফোন নম্বর" value="<?= htmlspecialchars($father_phone ?? '') ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">মায়ের ফোন নম্বর</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-phone"></i></span>
                                        <input type="text" name="mother_phone" class="form-control" placeholder="মায়ের ফোন নম্বর" value="<?= htmlspecialchars($mother_phone ?? '') ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">মায়ের নাম</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                                    <input type="text" name="mother_name" class="form-control" placeholder="মায়ের নাম" value="<?= htmlspecialchars($mother_name ?? '') ?>">
                                </div>
                            </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 (Simple version without filters) -->
                            <div class="mb-4">
                                <label class="form-label">আপনার সন্তান (ছাত্র/ছাত্রী) নির্বাচন করুন:</label>
                                <div class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
                                    <?php if (count($students) > 0): ?>
                                        <?php foreach ($students as $student): ?>
                                            <div class="student-checkbox">
                                                <div class="form-check">
                                                    <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'] ?>">
                                                        <strong><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></strong> - 
                                                        ক্লাস: <?= htmlspecialchars($student['class_name']) ?>, 
                                                        রোল: <?= $student['roll_number'] ?>,
                                                        সেশন: <?= htmlspecialchars($student['session'] ?? 'N/A') ?>,
                                                        গ্রুপ: <?= htmlspecialchars($student['group_name'] ?? 'N/A') ?>
                                                    </label>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <p class="text-muted">কোনো ছাত্র/ছাত্রী পাওয়া যায়নি। অনুগ্রহ করে স্কুল অফিসে যোগাযোগ করুন।</p>
                                    <?php endif; ?>
                                </div>
                                <div class="form-text">আপনার সন্তান না পেলে স্কুল অফিসে যোগাযোগ করুন।</div>
                            </div>
                            
                            <button type="submit" class="btn btn-register btn-primary w-100 mb-3">
                                <i class="fas fa-user-plus"></i> নিবন্ধন করুন
                            </button>
                            
                            <div class="text-center">
                                <p>ইতিমধ্যে একাউন্ট আছে? <a href="parent_login.php">লগইন করুন</a></p>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div class="text-center text-white mt-3">
                    <small>&copy; <?= date('Y') ?> <?= APP_NAME ?>. সর্বস্বত্ব সংরক্ষিত।</small>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>