<?php
session_start();
require_once 'config.php';

// If already logged in, redirect to dashboard
if (isset($_SESSION['patient_id'])) {
    header('Location: my_appointments.php');
    exit;
}

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

// Handle Login
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {
    $phone = mysqli_real_escape_string($conn, trim($_POST['phone']));
    $password = $_POST['password']; // Don't escape password before verification
    
    // Check if patient exists
    $query = "SELECT id, name, phone, email, password FROM patients WHERE phone = '$phone' OR email = '$phone'";
    $result = mysqli_query($conn, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $patient = mysqli_fetch_assoc($result);
        
        // Verify password (supports both plain text and hashed)
        $password_valid = false;
        
        // Check if password is hashed (starts with $2y$)
        if (strpos($patient['password'], '$2y$') === 0) {
            // Hashed password (using password_hash)
            $password_valid = password_verify($password, $patient['password']);
        } else {
            // Plain text password (for backward compatibility)
            $password_valid = ($password === $patient['password']);
            
            // If plain text matches, upgrade to hashed
            if ($password_valid) {
                $hashed = password_hash($password, PASSWORD_DEFAULT);
                $update_query = "UPDATE patients SET password = '$hashed' WHERE id = {$patient['id']}";
                mysqli_query($conn, $update_query);
            }
        }
        
        if ($password_valid) {
            $_SESSION['patient_id'] = $patient['id'];
            $_SESSION['patient_name'] = $patient['name'];
            $_SESSION['patient_phone'] = $patient['phone'];
            $_SESSION['patient_email'] = $patient['email'] ?? '';
            
            // Redirect to appointments
            header('Location: my_appointments.php');
            exit;
        } else {
            $error = 'ভুল পাসওয়ার্ড। আবার চেষ্টা করুন।';
        }
    } else {
        $error = 'এই মোবাইল নম্বর বা ইমেইল দিয়ে কোনো রোগী পাওয়া যায়নি।';
    }
}

// Handle Registration
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register'])) {
    $name = mysqli_real_escape_string($conn, trim($_POST['reg_name']));
    $phone = mysqli_real_escape_string($conn, trim($_POST['reg_phone']));
    $email = mysqli_real_escape_string($conn, trim($_POST['reg_email'] ?? ''));
    $password = $_POST['reg_password'];
    $confirm_password = $_POST['reg_confirm_password'];
    $address = mysqli_real_escape_string($conn, trim($_POST['reg_address'] ?? ''));
    
    // Validation
    $errors = [];
    if (empty($name)) $errors[] = "নাম দিন";
    if (empty($phone)) $errors[] = "মোবাইল নম্বর দিন";
    if (strlen($password) < 6) $errors[] = "পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে";
    if ($password !== $confirm_password) $errors[] = "পাসওয়ার্ড মিলছে না";
    
    // Check if phone already exists
    $check = mysqli_query($conn, "SELECT id FROM patients WHERE phone = '$phone'");
    if (mysqli_num_rows($check) > 0) {
        $errors[] = "এই মোবাইল নম্বরটি ইতিমধ্যে রেজিস্টার করা আছে";
    }
    
    if (empty($errors)) {
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        $query = "INSERT INTO patients (name, phone, email, password, address) 
                  VALUES ('$name', '$phone', '$email', '$hashed_password', '$address')";
        
        if (mysqli_query($conn, $query)) {
            $patient_id = mysqli_insert_id($conn);
            $_SESSION['patient_id'] = $patient_id;
            $_SESSION['patient_name'] = $name;
            $_SESSION['patient_phone'] = $phone;
            $_SESSION['patient_email'] = $email;
            
            $success = "রেজিস্ট্রেশন সফল! অ্যাপয়েন্টমেন্ট পেজে যাচ্ছি...";
            header('Refresh: 2; URL=my_appointments.php');
        } else {
            $error = "রেজিস্ট্রেশন ব্যর্থ: " . mysqli_error($conn);
        }
    } else {
        $error = implode('<br>', $errors);
    }
}

// If there's an error from session (from other pages)
if (isset($_SESSION['login_error'])) {
    $error = $_SESSION['login_error'];
    unset($_SESSION['login_error']);
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>রোগী লগইন - ডা. মোঃ ফেরদৌস</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: linear-gradient(135deg, #1a5276, #2e86c1);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'SolaimanLipi', Arial, sans-serif;
            padding: 20px;
        }
        .auth-card {
            max-width: 450px;
            width: 100%;
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            animation: slideUp 0.5s ease;
        }
        @keyframes slideUp {
            from { transform: translateY(30px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        .auth-card .logo {
            text-align: center;
            margin-bottom: 25px;
        }
        .auth-card .logo i {
            font-size: 50px;
            color: #1a5276;
            background: #eaf4f9;
            padding: 20px;
            border-radius: 50%;
        }
        .auth-card h3 {
            color: #1a5276;
            text-align: center;
            margin-bottom: 5px;
            font-weight: 700;
        }
        .auth-card .subtitle {
            text-align: center;
            color: #6c757d;
            margin-bottom: 25px;
            font-size: 14px;
        }
        .form-control {
            border-radius: 12px;
            padding: 12px 16px;
            border: 2px solid #e8ecf1;
            transition: all 0.3s;
        }
        .form-control:focus {
            border-color: #1a5276;
            box-shadow: 0 0 0 4px rgba(26, 82, 118, 0.1);
        }
        .btn-primary {
            background: linear-gradient(135deg, #1a5276, #2e86c1);
            border: none;
            padding: 12px;
            font-weight: 600;
            border-radius: 12px;
            width: 100%;
            transition: all 0.3s;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 25px rgba(26, 82, 118, 0.3);
        }
        .btn-outline-primary {
            border-radius: 12px;
            padding: 12px;
            font-weight: 600;
            width: 100%;
            border-color: #1a5276;
            color: #1a5276;
        }
        .btn-outline-primary:hover {
            background: #1a5276;
            color: white;
        }
        .tab-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 25px;
        }
        .tab-buttons .btn {
            flex: 1;
            border-radius: 12px;
            padding: 10px;
            font-weight: 600;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6c757d;
        }
        .password-toggle:hover { color: #1a5276; }
        .input-group { position: relative; }
        .alert { border-radius: 12px; }
        .back-link {
            display: block;
            text-align: center;
            margin-top: 15px;
            color: #6c757d;
            text-decoration: none;
            font-size: 14px;
        }
        .back-link:hover { color: #1a5276; }
        .forgot-link {
            display: block;
            text-align: right;
            font-size: 13px;
            margin-top: 5px;
            color: #6c757d;
        }
        .forgot-link:hover { color: #1a5276; }
        .divider {
            display: flex;
            align-items: center;
            margin: 20px 0;
            color: #adb5bd;
            font-size: 13px;
        }
        .divider::before, .divider::after {
            content: "";
            flex: 1;
            height: 1px;
            background: #dee2e6;
        }
        .divider::before { margin-right: 15px; }
        .divider::after { margin-left: 15px; }
    </style>
</head>
<body>

<div class="auth-card">
    <div class="logo">
        <i class="fas fa-user-md"></i>
    </div>
    <h3>🔐 রোগী লগইন</h3>
    <p class="subtitle">ডা. মোঃ ফেরদৌস - হোমিওপ্যাথি বিশেষজ্ঞ</p>

    <!-- Tab Buttons -->
    <div class="tab-buttons">
        <button class="btn btn-primary" id="loginTabBtn" onclick="switchTab('login')">
            <i class="fas fa-sign-in-alt"></i> লগইন
        </button>
        <button class="btn btn-outline-primary" id="registerTabBtn" onclick="switchTab('register')">
            <i class="fas fa-user-plus"></i> রেজিস্টার
        </button>
    </div>

    <!-- Error/Success Messages -->
    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($success): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?php echo $success; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Login Tab -->
    <div class="tab-content active" id="loginTab">
        <form method="post" action="">
            <div class="mb-3">
                <label class="form-label fw-bold">মোবাইল নম্বর বা ইমেইল</label>
                <div class="input-group">
                    <input type="text" name="phone" class="form-control" placeholder="017XXXXXXXX বা email@example.com" required>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label fw-bold">পাসওয়ার্ড</label>
                <div class="input-group">
                    <input type="password" name="password" id="loginPassword" class="form-control" placeholder="পাসওয়ার্ড দিন" required>
                    <span class="password-toggle" onclick="togglePassword('loginPassword')">
                        <i class="fas fa-eye"></i>
                    </span>
                </div>
                <a href="#" class="forgot-link" onclick="alert('পাসওয়ার্ড রিসেট করতে admin@drmdferdous.com এ মেইল করুন')">
                    <i class="fas fa-key"></i> পাসওয়ার্ড ভুলে গেছেন?
                </a>
            </div>
            <button type="submit" name="login" class="btn btn-primary">
                <i class="fas fa-sign-in-alt"></i> লগইন করুন
            </button>
        </form>
        
        <div class="divider">অথবা</div>
        
        <div class="text-center">
            <a href="/" class="back-link">
                <i class="fas fa-arrow-left"></i> হোমপেজে ফিরুন
            </a>
        </div>
    </div>

    <!-- Register Tab -->
    <div class="tab-content" id="registerTab">
        <form method="post" action="">
            <div class="mb-2">
                <label class="form-label fw-bold">পূর্ণ নাম *</label>
                <input type="text" name="reg_name" class="form-control" placeholder="আপনার নাম" required>
            </div>
            <div class="mb-2">
                <label class="form-label fw-bold">মোবাইল নম্বর *</label>
                <input type="text" name="reg_phone" class="form-control" placeholder="017XXXXXXXX" required>
            </div>
            <div class="mb-2">
                <label class="form-label fw-bold">ইমেইল (ঐচ্ছিক)</label>
                <input type="email" name="reg_email" class="form-control" placeholder="email@example.com">
            </div>
            <div class="mb-2">
                <label class="form-label fw-bold">পাসওয়ার্ড *</label>
                <div class="input-group">
                    <input type="password" name="reg_password" id="regPassword" class="form-control" placeholder="কমপক্ষে ৬ অক্ষর" required minlength="6">
                    <span class="password-toggle" onclick="togglePassword('regPassword')">
                        <i class="fas fa-eye"></i>
                    </span>
                </div>
            </div>
            <div class="mb-2">
                <label class="form-label fw-bold">পাসওয়ার্ড নিশ্চিত করুন *</label>
                <div class="input-group">
                    <input type="password" name="reg_confirm_password" id="regConfirmPassword" class="form-control" placeholder="আবার পাসওয়ার্ড দিন" required>
                    <span class="password-toggle" onclick="togglePassword('regConfirmPassword')">
                        <i class="fas fa-eye"></i>
                    </span>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label fw-bold">ঠিকানা (ঐচ্ছিক)</label>
                <textarea name="reg_address" class="form-control" rows="2" placeholder="আপনার ঠিকানা"></textarea>
            </div>
            <button type="submit" name="register" class="btn btn-primary">
                <i class="fas fa-user-plus"></i> রেজিস্ট্রেশন করুন
            </button>
        </form>
        
        <div class="text-center mt-3">
            <small class="text-muted">ইতিমধ্যে অ্যাকাউন্ট আছে? <a href="#" onclick="switchTab('login')">লগইন করুন</a></small>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// --- Tab Switching ---
function switchTab(tab) {
    document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
    document.getElementById(tab + 'Tab').classList.add('active');
    
    const loginBtn = document.getElementById('loginTabBtn');
    const registerBtn = document.getElementById('registerTabBtn');
    
    if (tab === 'login') {
        loginBtn.className = 'btn btn-primary';
        registerBtn.className = 'btn btn-outline-primary';
    } else {
        loginBtn.className = 'btn btn-outline-primary';
        registerBtn.className = 'btn btn-primary';
    }
}

// --- Toggle Password Visibility ---
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const icon = input.nextElementSibling.querySelector('i');
    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'fas fa-eye';
    }
}

// --- Password Match Validation for Registration ---
document.querySelector('form[action=""]').addEventListener('submit', function(e) {
    const password = document.getElementById('regPassword');
    const confirm = document.getElementById('regConfirmPassword');
    
    if (password && confirm && password.value !== confirm.value) {
        e.preventDefault();
        alert('পাসওয়ার্ড মিলছে না। আবার চেষ্টা করুন।');
        confirm.focus();
    }
});

// --- Auto-dismiss alerts ---
setTimeout(() => {
    document.querySelectorAll('.alert').forEach(el => {
        const alert = new bootstrap.Alert(el);
        alert.close();
    });
}, 5000);

// --- Show registration tab if URL has ?register ---
if (window.location.search.includes('register')) {
    switchTab('register');
}
</script>

</body>
</html>