<?php
include '../config/config.php';
include '../includes/auth.php'; // Ensure only admin can access

// --- 1. HANDLE ADDING NEW MEMBER ---
if (isset($_POST['add_user'])) {
    $full_name = htmlspecialchars($_POST['full_name']);
    $username  = htmlspecialchars($_POST['username']);
    $email     = htmlspecialchars($_POST['email']);
    $phone     = htmlspecialchars($_POST['phone']);
    $plain_pass = $_POST['password']; // Keep for the email body
    $password  = password_hash($plain_pass, PASSWORD_DEFAULT); 
    
    // Profile Picture Logic
    $profile_pic = "default.png";
    if (!empty($_FILES["profile_pic"]["name"])) {
        $target_dir = "../uploads/profiles/";
        if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
        
        $file_name = "user_" . time() . "_" . basename($_FILES["profile_pic"]["name"]);
        if (move_uploaded_file($_FILES["profile_pic"]["tmp_name"], $target_dir . $file_name)) {
            $profile_pic = $file_name;
        }
    }

    try {
        $sql = "INSERT INTO users (username, full_name, email, phone, password, profile_pic, role) VALUES (?, ?, ?, ?, ?, ?, 'member')";
        $stmt = $pdo->prepare($sql);
        
        if ($stmt->execute([$username, $full_name, $email, $phone, $password, $profile_pic])) {
            
            // --- MAILCHIMP API NOTIFICATION (Bypasses Port 25 Warning) ---
            $apiKey = 'YOUR_MAILCHIMP_API_KEY'; 
            $serverPrefix = 'us21'; 
            $url = "https://{$serverPrefix}.api.mailchimp.com/3.0/messages/send";
            $loginUrl = BASE_URL . "index.php";

            $htmlContent = "
                <div style='font-family: Arial, sans-serif; padding: 20px; border: 2px solid #e50914; max-width: 600px;'>
                    <h2 style='color: #e50914;'>Welcome to Swarnavahini Ratings</h2>
                    <p>Hello <strong>$full_name</strong>,</p>
                    <p>An account has been created for you. Use the credentials below to log in:</p>
                    <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; border-left: 4px solid #e50914;'>
                        <p><strong>Portal URL:</strong> <a href='$loginUrl'>$loginUrl</a></p>
                        <p><strong>Username:</strong> $username</p>
                        <p><strong>Password:</strong> $plain_pass</p>
                    </div>
                </div>";

            $data = ["key" => $apiKey, "message" => [
                "html" => $htmlContent, 
                "subject" => "Your New Swarnavahini Account Credentials",
                "from_email" => "portal@swarnavahini.lk", 
                "from_name" => "Swarnavahini Admin",
                "to" => [["email" => $email, "type" => "to"]]
            ]];

            // Stream Context uses HTTPS (Port 443) instead of SMTP (Port 25)
            $options = [
                'http' => [
                    'header' => "Content-type: application/json\r\nAuthorization: Basic " . base64_encode("user:$apiKey") . "\r\n",
                    'method' => 'POST', 
                    'content' => json_encode($data), 
                    'ignore_errors' => true
                ], 
                'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]
            ];

            $context = stream_context_create($options);
            
            // The '@' suppresses warnings if the API key is not yet set
            @file_get_contents($url, false, $context);

            $success_msg = "Member $full_name added successfully and credentials sent to $email!";
        }
    } catch (PDOException $e) {
        $error_msg = "Error: Username or Email already exists.";
    }
}

// --- 2. HANDLE DELETE ---
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'member'")->execute([$id]);
    header("Location: manage_users.php");
    exit();
}

// --- 3. FETCH MEMBERS ---
$members = $pdo->query("SELECT * FROM users WHERE role = 'member' ORDER BY id DESC")->fetchAll();
?>

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

<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">Committee Members <span class="badge bg-secondary"><?= count($members) ?>/10</span></h2>
        <?php if(count($members) < 10): ?>
            <button class="btn btn-danger shadow-sm" data-bs-toggle="modal" data-bs-target="#userModal">
                <i class="bi bi-person-plus"></i> Add New Member
            </button>
        <?php else: ?>
            <button class="btn btn-secondary shadow-sm" disabled>Member Limit Reached</button>
        <?php endif; ?>
    </div>

    <?php if(isset($success_msg)): ?>
        <div class="alert alert-success border-0 shadow-sm"><?= $success_msg ?></div>
    <?php elseif(isset($error_msg)): ?>
        <div class="alert alert-danger border-0 shadow-sm"><?= $error_msg ?></div>
    <?php endif; ?>

    <div class="card border-0 shadow-sm">
        <div class="table-responsive">
            <table class="table align-middle mb-0">
                <thead class="table-light text-uppercase small">
                    <tr>
                        <th>Profile</th>
                        <th>Full Name</th>
                        <th>Contact info</th>
                        <th>Username</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($members as $user): ?>
                    <tr>
                        <td>
                            <img src="../uploads/profiles/<?= $user['profile_pic'] ?>" class="rounded-circle border" width="45" height="45" style="object-fit: cover;">
                        </td>
                        <td><strong><?= htmlspecialchars($user['full_name']) ?></strong></td>
                        <td>
                            <small class="d-block text-muted"><?= htmlspecialchars($user['email']) ?></small>
                            <small class="text-muted"><?= htmlspecialchars($user['phone']) ?></small>
                        </td>
                        <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($user['username']) ?></span></td>
                        <td class="text-end">
                            <a href="?delete=<?= $user['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Remove this member?')">
                                <i class="bi bi-trash"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST" enctype="multipart/form-data">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title">Register Committee Member</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label small fw-bold">Full Name</label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Username</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Phone</label>
                        <input type="text" name="phone" class="form-control" required>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold">Email Address</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold">Password</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold">Profile Picture</label>
                        <input type="file" name="profile_pic" class="form-control" accept="image/*">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" name="add_user" class="btn btn-danger w-100 shadow-sm">Create Account & Notify</button>
            </div>
        </form>
    </div>
</div>

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