<?php
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../config/logger.php';

// Check if user is logged in
if (!isLoggedIn()) {
    header("Location: ../login.php");
    exit;
}

// Check if user has appropriate role
$allowedRoles = ['choirmaster', 'society_secretary', 'society_treasurer'];
if (!in_array($_SESSION['role'], $allowedRoles)) {
    logWarning("Unauthorized access attempt to society dashboard", [
        'user_id' => $_SESSION['user_id'],
        'role' => $_SESSION['role']
    ]);
    header("Location: ../index.php");
    exit;
}

// Get society information
$societyId = $_SESSION['society_id'] ?? null;
$society = null;

if ($societyId) {
    // Get society details from database
    $stmt = $conn->prepare("SELECT s.*, c.name as circuit_name, c.id as circuit_id, 
                           d.name as diocese_name, d.id as diocese_id
                           FROM societies s
                           JOIN circuits c ON s.circuit_id = c.id
                           JOIN dioceses d ON c.diocese_id = d.id
                           WHERE s.id = ?");
    $stmt->bind_param("i", $societyId);
    $stmt->execute();
    $result = $stmt->get_result();
    $society = $result->fetch_assoc();
    $stmt->close();
    
    logInfo("Society dashboard accessed", [
        'user_id' => $_SESSION['user_id'],
        'society_id' => $societyId,
        'found_society' => !empty($society) ? 'yes' : 'no'
    ]);
} else {
    // Try to get society ID from user record
    $userId = $_SESSION['user_id'];
    $stmt = $conn->prepare("SELECT society_id FROM users WHERE id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    
    if ($user && $user['society_id']) {
        $societyId = $user['society_id'];
        $_SESSION['society_id'] = $societyId;
        
        // Get society details
        $stmt = $conn->prepare("SELECT s.*, c.name as circuit_name, c.id as circuit_id, 
                               d.name as diocese_name, d.id as diocese_id
                               FROM societies s
                               JOIN circuits c ON s.circuit_id = c.id
                               JOIN dioceses d ON c.diocese_id = d.id
                               WHERE s.id = ?");
        $stmt->bind_param("i", $societyId);
        $stmt->execute();
        $result = $stmt->get_result();
        $society = $result->fetch_assoc();
        $stmt->close();
        
        logInfo("Society dashboard accessed (society_id from user record)", [
            'user_id' => $_SESSION['user_id'],
            'society_id' => $societyId,
            'found_society' => !empty($society) ? 'yes' : 'no'
        ]);
    } else {
        // Try to get society ID from member association
        $stmt = $conn->prepare("SELECT s.*, c.name as circuit_name, c.id as circuit_id, 
                               d.name as diocese_name, d.id as diocese_id
                               FROM members m
                               JOIN societies s ON m.society_id = s.id
                               JOIN circuits c ON s.circuit_id = c.id
                               JOIN dioceses d ON c.diocese_id = d.id
                               JOIN users u ON m.id = u.member_id
                               WHERE u.id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $society = $result->fetch_assoc();
        $stmt->close();
        
        if ($society) {
            $societyId = $society['id'];
            $_SESSION['society_id'] = $societyId;
            
            // Update user record with society_id
            $stmt = $conn->prepare("UPDATE users SET society_id = ? WHERE id = ?");
            $stmt->bind_param("ii", $societyId, $userId);
            $stmt->execute();
            $stmt->close();
            
            logInfo("Society dashboard accessed (society_id from member association)", [
                'user_id' => $_SESSION['user_id'],
                'society_id' => $societyId
            ]);
        } else {
            logError("Society user without society association", [
                'user_id' => $_SESSION['user_id'],
                'role' => $_SESSION['role']
            ]);
        }
    }
}

// If society not found, show error
if (!$society) {
    $_SESSION['alert_type'] = 'danger';
    $_SESSION['alert_message'] = 'Your account is not properly configured. Please contact the administrator.';
    header("Location: ../index.php");
    exit;
}

// Store circuit and diocese IDs in session for use in other pages
if (!isset($_SESSION['circuit_id']) && isset($society['circuit_id'])) {
    $_SESSION['circuit_id'] = $society['circuit_id'];
}
if (!isset($_SESSION['diocese_id']) && isset($society['diocese_id'])) {
    $_SESSION['diocese_id'] = $society['diocese_id'];
}

$pageTitle = $society['name'] . " Society Dashboard";
include_once '../includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800"><?php echo $society['name']; ?> Society Dashboard</h1>
    
    <div class="row">
        <!-- Circuit Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                Circuit</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $society['circuit_name']; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-church fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Diocese Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Diocese</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $society['diocese_name']; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-cathedral fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Members Count Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                Members</div>
                            <?php
                            // Get member count
                            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM members WHERE society_id = ?");
                            $stmt->bind_param("i", $societyId);
                            $stmt->execute();
                            $memberCount = $stmt->get_result()->fetch_assoc()['count'];
                            $stmt->close();
                            ?>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $memberCount; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-users fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Pending Reports Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                Pending Reports</div>
                            <?php
                            // Get pending reports count for circuit
                            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM reports 
                                                  WHERE source_entity_id = ? AND source_entity_type = 'society' 
                                                  AND status = 'submitted'");
                            $stmt->bind_param("i", $societyId);
                            $stmt->execute();
                            $pendingReports = $stmt->get_result()->fetch_assoc()['count'];
                            $stmt->close();
                            ?>
                            <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $pendingReports; ?></div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-clipboard-list fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Members by Voice Part -->
    <div class="row">
        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Members by Voice Part</h6>
                </div>
                <div class="card-body">
                    <?php
                    // Get members by voice part
                    $stmt = $conn->prepare("SELECT vp.name as voice_part, COUNT(m.id) as count
                                          FROM members m
                                          JOIN voice_parts vp ON m.voice_part_id = vp.id
                                          WHERE m.society_id = ?
                                          GROUP BY vp.id, vp.name
                                          ORDER BY vp.name");
                    $stmt->bind_param("i", $societyId);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    if ($result->num_rows > 0) {
                        echo '<ul class="list-group">';
                        while ($voicePart = $result->fetch_assoc()) {
                            echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
                            echo htmlspecialchars($voicePart['voice_part']);
                            echo '<span class="badge badge-primary badge-pill">' . $voicePart['count'] . '</span>';
                            echo '</li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<p>No members found in this society.</p>';
                    }
                    $stmt->close();
                    ?>
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Recent Reports</h6>
                </div>
                <div class="card-body">
                    <?php
                    // Get recent reports
                    $stmt = $conn->prepare("SELECT r.*, rt.name as report_type_name, u.full_name as submitted_by_name
                                          FROM reports r
                                          JOIN report_types rt ON r.report_type_id = rt.id
                                          JOIN users u ON r.submitted_by = u.id
                                          WHERE r.source_entity_id = ? AND r.source_entity_type = 'society'
                                          ORDER BY r.submission_date DESC LIMIT 5");
                    $stmt->bind_param("i", $societyId);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    if ($result->num_rows > 0) {
                        echo '<ul class="list-group">';
                        while ($report = $result->fetch_assoc()) {
                            echo '<li class="list-group-item">';
                            echo '<div class="d-flex w-100 justify-content-between">';
                            echo '<h5 class="mb-1">' . htmlspecialchars($report['report_type_name']) . '</h5>';
                            echo '<small>' . date('M d, Y', strtotime($report['submission_date'])) . '</small>';
                            echo '</div>';
                            
                            // Get target entity name
                            $targetName = "";
                            if ($report['target_entity_type'] == 'circuit') {
                                $targetStmt = $conn->prepare("SELECT name FROM circuits WHERE id = ?");
                                $targetStmt->bind_param("i", $report['target_entity_id']);
                                $targetStmt->execute();
                                $targetResult = $targetStmt->get_result();
                                if ($targetRow = $targetResult->fetch_assoc()) {
                                    $targetName = $targetRow['name'] . ' Circuit';
                                }
                                $targetStmt->close();
                            }
                            
                            echo '<p class="mb-1">To: ' . htmlspecialchars($targetName) . '</p>';
                            echo '<p class="mb-1">Status: <span class="badge badge-' . 
                                 ($report['status'] == 'approved' ? 'success' : 
                                 ($report['status'] == 'rejected' ? 'danger' : 'warning')) . 
                                 '">' . ucfirst($report['status']) . '</span></p>';
                            echo '<small>Submitted by: ' . htmlspecialchars($report['submitted_by_name']) . '</small>';
                            echo '</li>';
                        }
                        echo '</ul>';
                    } else {
                        echo '<p>No recent reports found.</p>';
                    }
                    $stmt->close();
                    ?>
                </div>
            </div>
        </div>
    </div>
</div>

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