<?php
/**
 * JV Overseas Education - Student Registration
 * Single-file PHP with integrated HTML and backend logic
 * Matches design of original index.html
 */

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Initialize variables
$error = '';
$success = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $date_of_birth = $_POST['date_of_birth'] ?? '';
    $gender = $_POST['gender'] ?? '';
    $education_level = $_POST['education_level'] ?? '';
    $current_institution = trim($_POST['current_institution'] ?? '');
    $gpa = $_POST['gpa'] ?? '';
    $budget = $_POST['budget'] ?? '';
    
    // Validate form data
    if (empty($first_name) || empty($last_name) || empty($email) || empty($password)) {
        $error = "All required fields must be filled.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
    } elseif ($password !== $confirm_password) {
        $error = "Passwords do not match.";
    } elseif (strlen($password) < 6) {
        $error = "Password must be at least 6 characters long.";
    } elseif ($pdo->query("SELECT id FROM users WHERE email = '$email'")->fetch()) {
        $error = "An account with this email already exists.";
    } else {
        try {
            // Start transaction
            $pdo->beginTransaction();
            
            // Create user record
            $stmt = $pdo->prepare("INSERT INTO users (email, password_hash, user_type, is_active, created_at, updated_at) 
                                  VALUES (?, ?, 'student', 1, NOW(), NOW())");
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt->execute([$email, $password_hash]);
            $user_id = $pdo->lastInsertId();
            
            // Create student profile
            $stmt = $pdo->prepare("INSERT INTO students (
                id, first_name, last_name, date_of_birth, gender, phone, 
                education_level, current_institution, gpa, budget, status, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'prospective', NOW(), NOW())");
            $stmt->execute([
                $user_id, $first_name, $last_name, $date_of_birth, $gender, $phone,
                $education_level, $current_institution, $gpa, $budget
            ]);
            
            // Commit transaction
            $pdo->commit();
            
            $success = "Registration successful! You can now login to your account.";
            
            // Clear form data
            $_POST = array();
            
        } catch (Exception $e) {
            $pdo->rollback();
            $error = "Registration failed. Please try again.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Student Registration - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .register-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            background: linear-gradient(rgba(0,0,0,0.7), rgba(0,0,0,0.7)), url('img/header-bg.jpg');
            background-size: cover;
        }
        .register-box {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 40px;
            max-width: 800px;
            width: 100%;
            margin: 0 auto;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        .logo {
            text-align: center;
            margin-bottom: 30px;
        }
        .logo img {
            height: 60px;
        }
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .section-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3fb7fe;
        }
    </style>
</head>
<body>
    <div class="container-fluid register-container">
        <div class="container">
            <div class="register-box">
                <div class="logo">
                    <img src="img/jhoverseas.jpg" alt="JV Overseas">
                </div>
                
                <h2 class="text-center text-primary mb-4">Student Registration</h2>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
                    <div class="text-center">
                        <a href="student-dashboard.php" class="btn btn-primary">Go to Login</a>
                    </div>
                <?php else: ?>
                    <form method="POST">
                        <div class="form-section">
                            <h5 class="section-title">Personal Information</h5>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label>First Name *</label>
                                    <input type="text" name="first_name" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['first_name'] ?? '') ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Last Name *</label>
                                    <input type="text" name="last_name" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['last_name'] ?? '') ?>" required>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label>Email Address *</label>
                                    <input type="email" name="email" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Phone Number</label>
                                    <input type="text" name="phone" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label>Date of Birth</label>
                                    <input type="date" name="date_of_birth" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['date_of_birth'] ?? '') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Gender</label>
                                    <select name="gender" class="form-control">
                                        <option value="">Select Gender</option>
                                        <option value="male" <?= ($_POST['gender'] ?? '') == 'male' ? 'selected' : '' ?>>Male</option>
                                        <option value="female" <?= ($_POST['gender'] ?? '') == 'female' ? 'selected' : '' ?>>Female</option>
                                        <option value="other" <?= ($_POST['gender'] ?? '') == 'other' ? 'selected' : '' ?>>Other</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h5 class="section-title">Academic Background</h5>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label>Current Education Level</label>
                                    <select name="education_level" class="form-control">
                                        <option value="">Select Level</option>
                                        <option value="High School" <?= ($_POST['education_level'] ?? '') == 'High School' ? 'selected' : '' ?>>High School</option>
                                        <option value="Diploma" <?= ($_POST['education_level'] ?? '') == 'Diploma' ? 'selected' : '' ?>>Diploma</option>
                                        <option value="Undergraduate" <?= ($_POST['education_level'] ?? '') == 'Undergraduate' ? 'selected' : '' ?>>Undergraduate</option>
                                        <option value="Postgraduate" <?= ($_POST['education_level'] ?? '') == 'Postgraduate' ? 'selected' : '' ?>>Postgraduate</option>
                                        <option value="PhD" <?= ($_POST['education_level'] ?? '') == 'PhD' ? 'selected' : '' ?>>PhD</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Current Institution</label>
                                    <input type="text" name="current_institution" class="form-control" 
                                           value="<?= htmlspecialchars($_POST['current_institution'] ?? '') ?>">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label>GPA / Average Score</label>
                                    <input type="number" name="gpa" class="form-control" step="0.01" min="0" max="5"
                                           value="<?= htmlspecialchars($_POST['gpa'] ?? '') ?>" placeholder="e.g., 3.5">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Estimated Budget (USD)</label>
                                    <input type="number" name="budget" class="form-control" min="0"
                                           value="<?= htmlspecialchars($_POST['budget'] ?? '') ?>" placeholder="e.g., 20000">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h5 class="section-title">Account Security</h5>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label>Password *</label>
                                    <input type="password" name="password" class="form-control" required>
                                    <small class="form-text text-muted">Must be at least 6 characters</small>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Confirm Password *</label>
                                    <input type="password" name="confirm_password" class="form-control" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="terms" name="terms" required>
                                <label class="custom-control-label" for="terms">
                                    I agree to the <a href="terms.html" target="_blank">Terms of Service</a> and <a href="privacy.html" target="_blank">Privacy Policy</a>
                                </label>
                            </div>
                        </div>
                        
                        <div class="text-center">
                            <button type="submit" class="btn btn-primary btn-lg px-5">Register Account</button>
                        </div>
                        
                        <div class="text-center mt-3">
                            <p>Already have an account? <a href="student-dashboard.php">Login here</a></p>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <div class="container-fluid bg-dark text-white-50 py-2">
        <div class="container text-center">
            <p class="mb-0">© <span id="year"></span> JV Overseas Education Uganda. All Rights Reserved.</p>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('year').textContent = new Date().getFullYear();
    </script>
</body>
</html>