<?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']; 
    $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])) {
            
            // --- MANDRILL TRANSACTIONAL NOTIFICATIONS ---
            $mandrill_key = 'md-Vjza4GhgRIEoal3e-KKkmw';
            $url = "https://mandrillapp.com/api/1.0/messages/send.json";
            $loginUrl = BASE_URL . "index.php";
            $joinDate = date("F j, Y");
            $joinTime = date("g:i a");

            $html_private = "
                <div style='font-family: Arial; padding: 20px; border: 2px solid #e50914; max-width: 600px;'>
                    <h2 style='color: #e50914;'>Welcome to Swarnavahini Ratings</h2>
                    <p>Hello <strong>$full_name</strong>, your account is ready.</p>
                    <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; border-left: 4px solid #e50914;'>
                        <p><strong>Login URL:</strong> <a href='$loginUrl'>$loginUrl</a></p>
                        <p><strong>Username:</strong> $username</p>
                        <p><strong>Password:</strong> $plain_pass</p>
                    </div>
                    <p style='font-size: 12px; color: #777; margin-top: 15px;'>Generated on: $joinDate at $joinTime</p>
                </div>";

            $html_announcement = "
                <div style='font-family: Arial; padding: 20px; border: 2px solid #333; max-width: 600px;'>
                    <h2 style='color: #333;'>New Committee Member</h2>
                    <p>Hi Team, please welcome our newest member to the ratings board.</p>
                    <div style='background: #f1f1f1; padding: 15px; border-radius: 5px;'>
                        <p><strong>Name:</strong> $full_name</p>
                        <p><strong>Joined Date:</strong> $joinDate</p>
                        <p><strong>Joined Time:</strong> $joinTime</p>
                    </div>
                </div>";

            $stmt_all = $pdo->query("SELECT email FROM users WHERE role = 'member' AND email != '$email'");
            $existing_emails = $stmt_all->fetchAll(PDO::FETCH_COLUMN);
            
            function sendMandrillMail($apiUrl, $payload) {
                $options = [
                    'http' => [
                        'header'  => "Content-type: application/json\r\n",
                        'method'  => 'POST',
                        'content' => json_encode($payload),
                        'ignore_errors' => true
                    ],
                    'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]
                ];
                $context = stream_context_create($options);
                return @file_get_contents($apiUrl, false, $context);
            }

            $private_payload = [
                "key" => $mandrill_key,
                "message" => [
                    "html" => $html_private, 
                    "subject" => "Your Swarnavahini Rating Credentials",
                    "from_email" => "teldramaratings@test.athavaneng.com", 
                    "from_name" => "Swarnavahini Admin",
                    "to" => [["email" => $email, "type" => "to"]]
                ]
            ];
            sendMandrillMail($url, $private_payload);

            if (!empty($existing_emails)) {
                $team_to_list = array_map(function($e) { return ["email" => $e, "type" => "to"]; }, $existing_emails);
                $announcement_payload = [
                    "key" => $mandrill_key,
                    "message" => [
                        "html" => $html_announcement, 
                        "subject" => "Welcome $full_name to the Team",
                        "from_email" => "teldramaratings@test.athavaneng.com", 
                        "from_name" => "Swarnavahini Admin",
                        "to" => $team_to_list
                    ]
                ];
                sendMandrillMail($url, $announcement_payload);
            }

            $success_msg = "Member registered and notifications sent!";
        }
    } 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?deleted=1");
    exit();
}

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

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 text-white">Committee Members <span class="badge bg-danger"><?= count($members) ?>/10</span></h2>
        <?php if(count($members) < 10): ?>
            <button class="btn btn-danger shadow-sm fw-bold" data-bs-toggle="modal" data-bs-target="#userModal">
                <i class="bi bi-person-plus me-1"></i> Add 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 bg-success text-white mb-4"><?= $success_msg ?></div>
    <?php endif; ?>
    
    <?php if(isset($_GET['updated'])): ?>
        <div class="alert alert-info border-0 shadow-sm bg-info text-dark fw-bold mb-4">Member updated successfully!</div>
    <?php endif; ?>

    <?php if(isset($error_msg)): ?>
        <div class="alert alert-danger border-0 shadow-sm bg-danger text-white mb-4"><?= $error_msg ?></div>
    <?php endif; ?>

    <div class="card border-0 shadow-sm bg-dark">
        <div class="table-responsive">
            <table class="table table-dark table-hover align-middle mb-0">
                <thead class="text-uppercase small text-white-50">
                    <tr>
                        <th class="ps-4">Profile</th>
                        <th>Full Name</th>
                        <th>Contact info</th>
                        <th>Username</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($members as $user): ?>
                    <tr style="border-bottom: 1px solid #333;">
                        <td class="ps-4">
                            <img src="../uploads/profiles/<?= $user['profile_pic'] ?>" class="rounded-circle border border-secondary" width="45" height="45" style="object-fit: cover;">
                        </td>
                        <td><strong class="text-white"><?= htmlspecialchars($user['full_name']) ?></strong></td>
                        <td>
                            <small class="d-block text-white-50"><?= htmlspecialchars($user['email']) ?></small>
                            <small class="text-muted"><?= htmlspecialchars($user['phone']) ?></small>
                        </td>
                        <td><span class="badge bg-black text-white border border-secondary"><?= htmlspecialchars($user['username']) ?></span></td>
                        <td class="text-end pe-4">
                            <a href="edit_user.php?id=<?= $user['id'] ?>" class="btn btn-sm btn-outline-info me-1">
                                <i class="bi bi-pencil-square"></i>
                            </a>
                            <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 bg-dark text-white border-secondary" method="POST" enctype="multipart/form-data">
            <div class="modal-header border-secondary bg-black">
                <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 p-4">
                <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 bg-black text-white border-secondary" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Username</label>
                        <input type="text" name="username" class="form-control bg-black text-white border-secondary" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Phone</label>
                        <input type="text" name="phone" class="form-control bg-black text-white border-secondary" required>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold">Email Address</label>
                        <input type="email" name="email" class="form-control bg-black text-white border-secondary" required>
                    </div>
                    <div class="col-12">
                        <label class="form-label small fw-bold">Password</label>
                        <input type="password" name="password" class="form-control bg-black text-white border-secondary" 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 bg-black text-white border-secondary" accept="image/*">
                    </div>
                </div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="submit" name="add_user" class="btn btn-danger w-100 fw-bold shadow">Create Account & Notify</button>
            </div>
        </form>
    </div>
</div>

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