<?php
include '../config/config.php';

// 1. Security Check
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: " . BASE_URL . "index.php");
    exit();
}

// 2. FETCH AUDIT DATA (Updated to count activity across episodes)
$member_stats = $pdo->query("SELECT u.id, u.full_name, u.username, u.last_login,
    COUNT(DISTINCT r.drama_id) as dramas_participated,
    COUNT(DISTINCT r.episode_id) as total_episodes_rated,
    SUM(r.watch_time_seconds) as total_seconds
    FROM users u
    LEFT JOIN ratings r ON u.id = r.user_id
    WHERE u.role = 'member'
    GROUP BY u.id
    ORDER BY total_episodes_rated DESC")->fetchAll();

$total_committee_time = $pdo->query("SELECT SUM(watch_time_seconds) FROM ratings")->fetchColumn() ?? 0;

// 3. HANDLE NEW MEMBER CREATION
if (isset($_POST['add_member'])) {
    $username = trim($_POST['username']);
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $password = $_POST['password']; 
    $hashed_pw = password_hash($password, PASSWORD_DEFAULT);
    
    try {
        $sql = "INSERT INTO users (username, full_name, email, password, role) VALUES (?, ?, ?, ?, 'member')";
        $stmt = $pdo->prepare($sql);
        
        if ($stmt->execute([$username, $full_name, $email, $hashed_pw])) {
            $mandrill_key = 'md-Vjza4GhgRIEoal3e-KKkmw'; 
            $url = "https://mandrillapp.com/api/1.0/messages/send.json";

            $htmlContent = "
                <div style='font-family: sans-serif; padding: 25px; border-top: 4px solid #e50914; max-width: 600px;'>
                    <h2 style='color: #e50914;'>Account Created: Swarnavahini Ratings</h2>
                    <p>Hello <strong>$full_name</strong>, your evaluator account is ready.</p>
                    <div style='background: #f8f9fa; padding: 15px; border-left: 5px solid #e50914;'>
                        <p><strong>Username:</strong> $username</p>
                        <p><strong>Password:</strong> $password</p>
                    </div>
                    <p><a href='".BASE_URL."' style='display:inline-block; margin-top:15px; background:#e50914; color:#fff; padding:10px 20px; text-decoration:none; border-radius:5px;'>Login to Portal</a></p>
                </div>";

            $data = ["key" => $mandrill_key, "message" => [
                "html" => $htmlContent, "subject" => "Your Swarnavahini Evaluator Credentials",
                "from_email" => ADMIN_EMAIL, "from_name" => "Swarnavahini Admin",
                "to" => [["email" => $email, "type" => "to"]]
            ]];

            $options = ['http' => [
                'header' => "Content-type: application/json\r\n",
                'method' => 'POST', 'content' => json_encode($data)
            ], 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]];

            $context = stream_context_create($options);
            @file_get_contents($url, false, $context);
            $success = "Member $full_name created successfully.";
        }
    } catch (PDOException $e) { $error = "Username or Email already exists."; }
}

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

<div class="container mt-4 mb-5">
    <div class="row align-items-center mb-4">
        <div class="col-md-6">
            <h2 class="text-white fw-bold mb-0">Committee Audit</h2>
            <p class="text-white-50">Member Activity & Engagement Tracking</p>
        </div>
        <div class="col-md-6 text-md-end">
            <button class="btn btn-danger fw-bold shadow" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                <i class="bi bi-person-plus me-1"></i> Add Member
            </button>
        </div>
    </div>

    <div class="row g-3 mb-5">

        <div class="col-md-6">
            <div class="card bg-dark border-secondary p-4 shadow-sm">
                <small class="text-muted text-uppercase fw-bold mb-1 d-block">Committee Members</small>
                <h3 class="text-white mb-0"><?= count($member_stats) ?> <span class="fs-6 text-white-50">Active Members</span></h3>
            </div>
        </div>
    </div>

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

    <div class="card bg-dark border-secondary shadow-lg">
        <div class="card-header border-secondary bg-black py-3">
            <h5 class="text-white mb-0">Member Productivity</h5>
        </div>
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0 align-middle">
                <thead class="small text-uppercase text-muted bg-black">
                    <tr>
                        <th class="ps-4">Evaluator</th>
                        <th>Status</th>
                        <th class="text-center">Teledramas rated</th>
                        <th class="text-center">Episodes Rated</th>
                        <th class="pe-4 text-end">Last Seen</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($member_stats as $ms): 
                        $is_online = (isset($ms['last_login']) && strtotime($ms['last_login']) > strtotime('-5 minutes'));
                    ?>
                    <tr class="border-secondary">
                        <td class="ps-4">
                            <span class="text-white fw-bold d-block"><?= htmlspecialchars($ms['full_name']) ?></span>
                            <small class="text-muted">@<?= htmlspecialchars($ms['username']) ?></small>
                        </td>
                        <td>
                            <?php if($is_online): ?>
                                <span class="badge bg-success small"><i class="bi bi-circle-fill me-1" style="font-size: 8px;"></i> Online</span>
                            <?php else: ?>
                                <span class="badge bg-secondary small text-white-50">Offline</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-center">
                            <span class="text-white fw-bold"><?= $ms['dramas_participated'] ?></span>
                        </td>
                        <td class="text-center">
                            <span class="badge bg-black border border-secondary text-info px-3 py-2">
                                <?= $ms['total_episodes_rated'] ?> <small class="text-muted">EPs</small>
                            </span>
                        </td>
                        <td class="pe-4 text-end">
                            <small class="text-white-50">
                                <?= $ms['last_login'] ? date('M d, g:i A', strtotime($ms['last_login'])) : 'Never' ?>
                            </small>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="addMemberModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content bg-dark text-white border-secondary" method="POST">
            <div class="modal-header border-secondary bg-black">
                <h5 class="modal-title">Register New 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="mb-3">
                    <label class="small text-white-50 fw-bold">Full Name</label>
                    <input type="text" name="full_name" class="form-control bg-black text-white border-secondary" required>
                </div>
                <div class="mb-3">
                    <label class="small text-white-50 fw-bold">Username</label>
                    <input type="text" name="username" class="form-control bg-black text-white border-secondary" required>
                </div>
                <div class="mb-3">
                    <label class="small text-white-50 fw-bold">Email</label>
                    <input type="email" name="email" class="form-control bg-black text-white border-secondary" required>
                </div>
                <div class="mb-3">
                    <label class="small text-white-50 fw-bold">Password</label>
                    <input type="text" name="password" class="form-control bg-black text-white border-secondary" value="SWR_<?= rand(100, 999) ?>" required>
                </div>
            </div>
            <div class="modal-footer border-secondary bg-black">
                <button type="submit" name="add_member" class="btn btn-danger w-100 fw-bold">Create Account & Notify</button>
            </div>
        </form>
    </div>
</div>

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