<?php
require_once 'includes/config.php';

if (isLoggedIn()) {
    header('Location: dashboard.php');
    exit;
}

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

// Get membership types
$stmt = $pdo->query("SELECT * FROM membership_types ORDER BY amount");
$membershipTypes = $stmt->fetchAll();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $fullname = trim($_POST['fullname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $dob = $_POST['dob'] ?? '';
    $gender = $_POST['gender'] ?? '';
    $address = trim($_POST['address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $pincode = trim($_POST['pincode'] ?? '');
    $occupation = trim($_POST['occupation'] ?? '');
    $membership_type_id = $_POST['membership_type_id'] ?? 0;
    
    // Validation
    if (empty($fullname) || empty($email) || empty($password) || empty($membership_type_id)) {
        $error = 'Please fill all required fields';
    } 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';
    } else {
        // Check if email exists
        $stmt = $pdo->prepare("SELECT id FROM members WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->rowCount() > 0) {
            $error = 'Email already registered';
        } else {
            // Get membership type details
            $stmt = $pdo->prepare("SELECT * FROM membership_types WHERE id = ?");
            $stmt->execute([$membership_type_id]);
            $membershipType = $stmt->fetch();
            
            // Generate membership number
            $membership_number = generateMembershipNumber();
            
            // Calculate expiry date
            $join_date = date('Y-m-d');
            $expiry_date = $membershipType['duration_months'] > 0 
                ? date('Y-m-d', strtotime("+{$membershipType['duration_months']} months")) 
                : null;
            
            // Handle photo upload
            $profile_photo = 'default.jpg';
            if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] == 0) {
                $uploadResult = uploadFile($_FILES['profile_photo']);
                if (isset($uploadResult['success'])) {
                    $profile_photo = $uploadResult['filename'];
                }
            }
            
            try {
                // Insert member
                $stmt = $pdo->prepare("INSERT INTO members (membership_number, fullname, email, password, phone, dob, gender, address, city, state, pincode, occupation, membership_type_id, profile_photo, join_date, expiry_date, status) 
                                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')");
                
                $stmt->execute([
                    $membership_number, $fullname, $email, md5($password), $phone, $dob, $gender,
                    $address, $city, $state, $pincode, $occupation, $membership_type_id,
                    $profile_photo, $join_date, $expiry_date
                ]);
                
                $memberId = $pdo->lastInsertId();
                
                // Create user account
                $stmt = $pdo->prepare("INSERT INTO users (email, password, role) VALUES (?, ?, 'member')");
                $stmt->execute([$email, md5($password)]);
                
                // Send welcome email
                $subject = "Welcome to " . SITE_NAME;
                $message = "
                <h2>Welcome $fullname!</h2>
                <p>Thank you for joining " . SITE_NAME . ". Your membership has been successfully registered.</p>
                <p><strong>Membership Number:</strong> $membership_number</p>
                <p><strong>Membership Type:</strong> {$membershipType['type']}</p>
                <p><strong>Valid Until:</strong> " . formatDate($expiry_date) . "</p>
                <p>You can now login to your dashboard to access your digital ID card and other benefits.</p>
                <p>Login URL: " . SITE_URL . "login.php</p>
                ";
                
                sendEmail($email, $subject, $message);
                
                $success = "Registration successful! Your membership number is: <strong>$membership_number</strong>";
                $_SESSION['registration_success'] = $success;
                header("Refresh: 3; url=login.php");
                
            } catch (Exception $e) {
                $error = 'Registration failed: ' . $e->getMessage();
            }
        }
    }
}
?>

<?php include 'header.php'; ?>

<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h4 class="mb-0"><i class="fas fa-user-plus me-2"></i>Member Registration</h4>
            </div>
            <div class="card-body">
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <?php echo $success; ?>
                        <div class="mt-2">Redirecting to login page...</div>
                    </div>
                <?php else: ?>
                <form method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Full Name *</label>
                                <input type="text" class="form-control" name="fullname" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Email *</label>
                                <input type="email" class="form-control" name="email" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Phone Number</label>
                                <input type="tel" class="form-control" name="phone">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Date of Birth</label>
                                <input type="date" class="form-control" name="dob">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Gender</label>
                                <select class="form-control" name="gender">
                                    <option value="">Select</option>
                                    <option value="male">Male</option>
                                    <option value="female">Female</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Membership Type *</label>
                                <select class="form-control" name="membership_type_id" required>
                                    <option value="">Select Membership Type</option>
                                    <?php foreach ($membershipTypes as $type): ?>
                                        <option value="<?php echo $type['id']; ?>">
                                            <?php echo $type['type']; ?> - <?php echo formatCurrency($type['amount']); ?>
                                            <?php if ($type['duration_months'] > 0): ?>
                                                (<?php echo $type['duration_months']; ?> months)
                                            <?php else: ?>
                                                (Lifetime)
                                            <?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Password *</label>
                                <input type="password" class="form-control" name="password" required minlength="6">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Confirm Password *</label>
                                <input type="password" class="form-control" name="confirm_password" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Profile Photo</label>
                                <input type="file" class="form-control" name="profile_photo" accept="image/*">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Occupation</label>
                                <input type="text" class="form-control" name="occupation">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="mb-3">
                                <label class="form-label">Address</label>
                                <textarea class="form-control" name="address" rows="2"></textarea>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">City</label>
                                <input type="text" class="form-control" name="city">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">State</label>
                                <input type="text" class="form-control" name="state">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">Pincode</label>
                                <input type="text" class="form-control" name="pincode">
                            </div>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary w-100">Register Now</button>
                    
                    <div class="text-center mt-3">
                        <p>Already have an account? <a href="login.php">Login here</a></p>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>