<?php
require_once 'config.php';

$message = $_GET['msg'] ?? '';

// Handle Logout
if (isset($_GET['logout'])) {
    session_destroy();
    session_start();
    $message = 'You have been successfully logged out.';
}

// Handle Login
if (isset($_POST['login'])) {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        // Successful Login
        $_SESSION['user_id'] = $user['id'];
        // Use first_name and last_name as defined in the new schema
        $full_name = $user['first_name'] . (isset($user['last_name']) ? ' ' . $user['last_name'] : '');
        $_SESSION['user_name'] = trim($full_name) ?: $user['first_name'];
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['image_url'] = $user['image_url'];

        // Redirect based on role
        if ($user['role'] === 'admin') {
            header('Location: dashboard.php');
        } else {
            header('Location: studentdash.php');
        }
        exit();
    } else {
        $message = 'Invalid email or password.';
    }
}

// Handle Registration
if (isset($_POST['register'])) {
    // Personal Information
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $phone_number = trim($_POST['phone_number']);
    $whatsapp_number = trim($_POST['whatsapp_number']);
    $nic_number = trim($_POST['nic_number']);
    $dob = trim($_POST['dob']);

    // School/Academic Information
    $school_name = trim($_POST['school_name']);
    $a_l_year = trim($_POST['a_l_year']);
    $media = trim($_POST['media']);
    $stream = trim($_POST['stream']);
    $institute = trim($_POST['institute']);

    // Delivery Information
    $address_line_1 = trim($_POST['address_line_1']);
    $address_line_2 = trim($_POST['address_line_2']);
    $city = trim($_POST['city']);
    $district = trim($_POST['district']);

    // Guardian Information
    $guardian_name = trim($_POST['guardian_name']);
    $guardian_phone = trim($_POST['guardian_phone']);

    // Validation (Mandatory fields: First Name, Email, Password, Phone Number)
    if (empty($first_name) || empty($email) || empty($password) || empty($phone_number)) {
        $message = 'Please fill in all mandatory fields (Name, Email, Password, Phone Number).';
    } else {
        try {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            // Prepare the comprehensive INSERT query
            $stmt = $pdo->prepare("
                INSERT INTO users (
                    first_name, last_name, email, password, phone_number, whatsapp_number, nic_number, dob, 
                    school_name, a_l_year, media, stream, institute,
                    address_line_1, address_line_2, city, district,
                    guardian_name, guardian_phone, role
                ) 
                VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, 
                    ?, ?, ?, ?, ?,
                    ?, ?, ?, ?,
                    ?, ?, 'student'
                )
            ");
            
            $stmt->execute([
                $first_name, $last_name, $email, $hashed_password, $phone_number, $whatsapp_number, $nic_number, $dob, 
                $school_name, $a_l_year, $media, $stream, $institute,
                $address_line_1, $address_line_2, $city, $district,
                $guardian_name, $guardian_phone
            ]);

            // Log registration event
            log_analytics($pdo, 'registration', $pdo->lastInsertId());

            $message = 'Registration successful! Please login.';
        } catch (PDOException $e) {
            // Check for duplicate entry error (code 23000) for email or NIC
            if ($e->getCode() === '23000') {
                $message = 'Registration failed: This email or NIC is already registered.';
            } else {
                // Log the actual error for debugging
                // error_log("Registration DB Error: " . $e->getMessage());
                $message = 'Registration failed due to a database error. Please try again.';
            }
        }
    }
}

require_once 'layouts.php';
render_header('Login/Register');
?>

<script src="https://cdn.tailwindcss.com"></script>
<style>
    /* Custom background pattern to mimic the screenshot */
    .lms-bg {
        background: linear-gradient(135deg, #4c51bf 0%, #6366f1 100%);
        background-attachment: fixed;
        position: relative;
        overflow: hidden;
    }
    .lms-bg::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: radial-gradient(circle, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
        background-size: 30px 30px;
        opacity: 0.5;
        pointer-events: none;
    }
    /* Custom input/select styles matching the requested design */
    .lms-input {
        border: 1px solid #d1d5db;
        border-radius: 8px;
        padding: 10px 14px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        transition: all 0.2s ease;
    }
    .lms-input:focus {
        outline: none;
        border-color: #4f46e5;
        box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.2);
    }
</style>

<div class="lms-bg min-h-screen flex items-center justify-center py-12 px-4">
    <script>
        // Toggle between Login and Register forms
        function toggleForm(showForm) {
            document.getElementById('login-form').classList.add('hidden');
            document.getElementById('register-form').classList.add('hidden');
            document.getElementById(showForm + '-form').classList.remove('hidden');
            
            // Update tab styles
            const loginTab = document.getElementById('login-tab');
            const registerTab = document.getElementById('register-tab');
            if (showForm === 'login') {
                loginTab.classList.add('bg-blue-600', 'text-white');
                loginTab.classList.remove('text-gray-600');
                registerTab.classList.remove('bg-blue-600', 'text-white');
                registerTab.classList.add('text-gray-600');
            } else {
                registerTab.classList.add('bg-blue-600', 'text-white');
                registerTab.classList.remove('text-gray-600');
                loginTab.classList.remove('bg-blue-600', 'text-white');
                loginTab.classList.add('text-gray-600');
            }
        }
    </script>
    
    <!-- Max width for the card is wider on desktop for the detailed registration form -->
    <div class="max-w-4xl w-full bg-white p-6 sm:p-10 rounded-2xl shadow-2xl">
        <h1 class="text-3xl font-extrabold text-center text-gray-900 mb-6 flex items-center justify-center">
            <span class="mr-2 text-4xl">🎓</span> Register/Login
        </h1>

        <!-- Messages -->
        <?php if ($message): ?>
            <div class="bg-blue-100 border-l-4 border-blue-500 text-blue-700 p-4 mb-4 rounded-lg" role="alert">
                <p><?php echo htmlspecialchars($message); ?></p>
            </div>
        <?php endif; ?>

        <!-- Tabs -->
        <div class="flex mb-8 bg-gray-100 rounded-xl p-1 shadow-inner">
            <button id="login-tab" onclick="toggleForm('login')" class="flex-1 py-3 px-4 rounded-lg font-bold transition duration-300 text-lg bg-blue-600 text-white shadow-md hover:bg-blue-700">Student Login</button>
            <button id="register-tab" onclick="toggleForm('register')" class="flex-1 py-3 px-4 rounded-lg font-bold transition duration-300 text-lg text-gray-600 hover:bg-gray-200">Register New Student</button>
        </div>

        <!-- Login Form (LMS Style) -->
        <form id="login-form" method="POST" action="index.php" class="space-y-6 max-w-sm mx-auto">
            <div>
                <label for="login_email" class="block text-sm font-semibold text-gray-700 mb-1">Email Address</label>
                <input id="login_email" name="email" type="email" required class="lms-input w-full" placeholder="name@example.com">
            </div>
            <div>
                <label for="login_password" class="block text-sm font-semibold text-gray-700 mb-1">Password</label>
                <input id="login_password" name="password" type="password" required class="lms-input w-full" placeholder="********">
            </div>
            <button type="submit" name="login" class="w-full flex justify-center py-3 px-4 border border-transparent rounded-xl shadow-lg text-lg font-bold text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-4 focus:ring-blue-300 transition duration-150 transform hover:scale-[1.01]">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"/>
                </svg>
                Sign In
            </button>
        </form>

        <!-- Register Form (Expanded and Responsive) -->
        <form id="register-form" method="POST" action="index.php" class="space-y-8 hidden">
            
            <!-- Personal Information -->
            <section>
                <h2 class="text-xl font-bold text-gray-800 border-b pb-2 mb-4 flex items-center">
                    <span class="mr-2 text-2xl">👤</span> Personal Information
                </h2>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    <div>
                        <label for="reg_first_name" class="block text-sm font-semibold text-gray-700 mb-1">First Name <span class="text-red-500">*</span></label>
                        <input id="reg_first_name" name="first_name" type="text" required class="lms-input w-full" placeholder="John">
                    </div>
                    <div>
                        <label for="reg_last_name" class="block text-sm font-semibold text-gray-700 mb-1">Last Name</label>
                        <input id="reg_last_name" name="last_name" type="text" class="lms-input w-full" placeholder="Doe">
                    </div>
                    <!-- Email and Password go here to keep them prominent -->
                    <div class="sm:col-span-2">
                        <label for="reg_email" class="block text-sm font-semibold text-gray-700 mb-1">Email Address <span class="text-red-500">*</span></label>
                        <input id="reg_email" name="email" type="email" required class="lms-input w-full" placeholder="john.doe@email.com">
                    </div>
                    <div class="sm:col-span-2">
                        <label for="reg_password" class="block text-sm font-semibold text-gray-700 mb-1">Password <span class="text-red-500">*</span></label>
                        <input id="reg_password" name="password" type="password" required class="lms-input w-full" placeholder="Must be at least 8 characters">
                    </div>
                    
                    <div>
                        <label for="reg_phone" class="block text-sm font-semibold text-gray-700 mb-1">Phone Number <span class="text-red-500">*</span></label>
                        <input id="reg_phone" name="phone_number" type="tel" required class="lms-input w-full" placeholder="07XXXXXXXX">
                    </div>
                    <div>
                        <label for="reg_whatsapp" class="block text-sm font-semibold text-gray-700 mb-1">WhatsApp Number</label>
                        <input id="reg_whatsapp" name="whatsapp_number" type="tel" class="lms-input w-full" placeholder="07XXXXXXXX">
                    </div>
                    <div>
                        <label for="reg_nic" class="block text-sm font-semibold text-gray-700 mb-1">NIC Card Number</label>
                        <input id="reg_nic" name="nic_number" type="text" class="lms-input w-full" placeholder="20XXXXXXXXXX (New Format)">
                    </div>
                    <div>
                        <label for="reg_dob" class="block text-sm font-semibold text-gray-700 mb-1">Date of Birth</label>
                        <input id="reg_dob" name="dob" type="date" class="lms-input w-full">
                    </div>
                </div>
            </section>

            <!-- School Information -->
            <section>
                <h2 class="text-xl font-bold text-gray-800 border-b pb-2 mb-4 flex items-center">
                    <span class="mr-2 text-2xl">🏫</span> School & Academic Information
                </h2>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    <div class="sm:col-span-2">
                        <label for="reg_school" class="block text-sm font-semibold text-gray-700 mb-1">School Name</label>
                        <input id="reg_school" name="school_name" type="text" class="lms-input w-full" placeholder="Ananda College / Museus College">
                    </div>
                    
                    <div>
                        <label for="reg_year" class="block text-sm font-semibold text-gray-700 mb-1">A/L Exam Year</label>
                        <input id="reg_year" name="a_l_year" type="text" placeholder="e.g., 2027" class="lms-input w-full">
                    </div>
                    
                    <div>
                        <label for="reg_media" class="block text-sm font-semibold text-gray-700 mb-1">Media</label>
                        <select id="reg_media" name="media" class="lms-input w-full">
                            <option value="">Select Media</option>
                            <option value="Sinhala">Sinhala</option>
                            <option value="Tamil">Tamil</option>
                            <option value="English">English</option>
                        </select>
                    </div>

                    <div>
                        <label for="reg_stream" class="block text-sm font-semibold text-gray-700 mb-1">Stream</label>
                        <select id="reg_stream" name="stream" class="lms-input w-full">
                            <option value="">Select Stream</option>
                            <option value="Mathematics">Mathematics</option>
                            <option value="Bio Science">Bio Science</option>
                            <option value="Commerce">Commerce</option>
                            <option value="Arts">Arts</option>
                            <option value="Technology">Technology</option>
                        </select>
                    </div>

                    <div>
                        <label for="reg_institute" class="block text-sm font-semibold text-gray-700 mb-1">Institute/Tuition Name</label>
                        <input id="reg_institute" name="institute" type="text" class="lms-input w-full" placeholder="Online / ABC Classes">
                    </div>
                </div>
            </section>

            <!-- Delivery/Address Information -->
            <section>
                <h2 class="text-xl font-bold text-gray-800 border-b pb-2 mb-4 flex items-center">
                    <span class="mr-2 text-2xl">📦</span> Delivery Information (Address)
                </h2>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    <div class="sm:col-span-2">
                        <label for="reg_addr1" class="block text-sm font-semibold text-gray-700 mb-1">Address Line 1</label>
                        <input id="reg_addr1" name="address_line_1" type="text" class="lms-input w-full" placeholder="No 000, Road Name">
                    </div>
                    <div class="sm:col-span-2">
                        <label for="reg_addr2" class="block text-sm font-semibold text-gray-700 mb-1">Address Line 2</label>
                        <input id="reg_addr2" name="address_line_2" type="text" class="lms-input w-full" placeholder="City Name">
                    </div>
                    
                    <div>
                        <label for="reg_city" class="block text-sm font-semibold text-gray-700 mb-1">City</label>
                        <input id="reg_city" name="city" type="text" class="lms-input w-full" placeholder="Colombo 05">
                    </div>
                    <div>
                        <label for="reg_district" class="block text-sm font-semibold text-gray-700 mb-1">District</label>
                        <input id="reg_district" name="district" type="text" class="lms-input w-full" placeholder="Colombo">
                    </div>
                </div>
            </section>

            <!-- Guardian Information -->
            <section>
                <h2 class="text-xl font-bold text-gray-800 border-b pb-2 mb-4 flex items-center">
                    <span class="mr-2 text-2xl">👨‍👩‍👧</span> Guardian Information
                </h2>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                    <div>
                        <label for="reg_gname" class="block text-sm font-semibold text-gray-700 mb-1">Guardian Name</label>
                        <input id="reg_gname" name="guardian_name" type="text" class="lms-input w-full" placeholder="Mrs. J. Doe">
                    </div>
                    
                    <div>
                        <label for="reg_gphone" class="block text-sm font-semibold text-gray-700 mb-1">Guardian Phone</label>
                        <input id="reg_gphone" name="guardian_phone" type="tel" class="lms-input w-full" placeholder="07XXXXXXXX">
                    </div>
                </div>
            </section>

            <!-- Submission and Footer -->
            <div class="pt-4 space-y-4">
                <div class="flex items-start">
                    <input id="terms_agree" name="terms_agree" type="checkbox" required class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded mt-1">
                    <label for="terms_agree" class="ml-3 block text-sm text-gray-900">
                        I agree to the <a href="#" class="text-blue-600 font-semibold hover:text-blue-700 transition duration-150">Terms and Conditions</a> <span class="text-red-500">*</span>
                    </label>
                </div>

                <button type="submit" name="register" class="w-full flex justify-center py-3 px-4 border border-transparent rounded-xl shadow-lg text-xl font-bold text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-4 focus:ring-blue-300 transition duration-150 transform hover:scale-[1.01]">
                    Register Account
                </button>

                <p class="text-center text-sm text-gray-500 pt-2">
                    Already have an account? 
                    <button type="button" onclick="toggleForm('login')" class="text-blue-600 font-semibold hover:text-blue-700 transition duration-150">Login!</button>
                </p>
                <p class="text-center text-xs text-gray-400">
                    Hotline : 0741783886
                </p>
            </div>
        </form>
    </div>
</div>

<script>
    // Ensure the form state is correct on load
    document.addEventListener('DOMContentLoaded', function() {
        const message = "<?php echo $message; ?>";
        // Default to register if there was a message (likely an error or success after submission)
        if (message.includes('Registration')) {
            toggleForm('register');
        } else {
            toggleForm('login'); // Default to login on first load
        }
    });
</script>

<?php render_footer(); ?>