<?php
/**
 * Society View - Display Society Details and Members
 * GHAMECC Choir Management Platform
 */

// Include necessary files
require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

// Set page title and base path for includes
$pageTitle = "Society Details";
$basePath = '..';

// Get user role and entity IDs
$userRole = $_SESSION['role'] ?? '';
$userSocietyId = $_SESSION['society_id'] ?? null;
$userCircuitId = $_SESSION['circuit_id'] ?? null;
$userDioceseId = $_SESSION['diocese_id'] ?? null;

// Get society ID from URL
$societyId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($societyId <= 0) {
    header('Location: index.php');
    exit;
}

// Initialize variables
$society = null;
$members = [];
$statistics = [];
$error = '';

// Check if user has permission to view this society
$hasPermission = false;
if ($userRole === 'admin') {
    $hasPermission = true;
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    // Check if society belongs to user's diocese
    $query = "SELECT s.id FROM societies s 
              JOIN circuits c ON s.circuit_id = c.id 
              WHERE s.id = ? AND c.diocese_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ii", $societyId, $userDioceseId);
    $stmt->execute();
    $result = $stmt->get_result();
    $hasPermission = $result->num_rows > 0;
    $stmt->close();
} elseif ($userRole === 'circuit_secretary' && !empty($userCircuitId)) {
    // Check if society belongs to user's circuit
    $query = "SELECT id FROM societies WHERE id = ? AND circuit_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ii", $societyId, $userCircuitId);
    $stmt->execute();
    $result = $stmt->get_result();
    $hasPermission = $result->num_rows > 0;
    $stmt->close();
} elseif ($userRole === 'society_secretary' && !empty($userSocietyId)) {
    $hasPermission = ($userSocietyId == $societyId);
}

if (!$hasPermission) {
    $error = "You do not have permission to view this society.";
} else {
    // Get society details
    $query = "SELECT s.*, c.name as circuit_name, d.name as diocese_name 
              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 = $conn->prepare($query);
    $stmt->bind_param("i", $societyId);
    $stmt->execute();
    $result = $stmt->get_result();
    $society = $result->fetch_assoc();
    $stmt->close();

    if (!$society) {
        $error = "Society not found.";
    } else {
        // Get all members in this society
        $query = "SELECT m.*,
                  CASE 
                    WHEN m.sex = 'Male' THEN 'Male'
                    WHEN m.sex = 'Female' THEN 'Female'
                    ELSE 'Not Specified'
                  END as gender_display,
                  CASE 
                    WHEN m.membership_status = 'Active' THEN 'Active'
                    WHEN m.membership_status = 'Inactive' THEN 'Inactive'
                    WHEN m.membership_status = 'Distance Member' THEN 'Distance Member'
                    ELSE 'Unknown'
                  END as status_display
                  FROM members m
                  WHERE m.society_id = ?
                  ORDER BY m.last_name, m.first_name";
        $stmt = $conn->prepare($query);
        
        if ($stmt === false) {
            error_log("SQL Prepare Error in societies/view.php: " . $conn->error);
            $error = "Database error occurred while fetching members.";
            $members = [];
        } else {
            $stmt->bind_param("i", $societyId);
            $stmt->execute();
            $result = $stmt->get_result();
            $members = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
        }

        // Calculate statistics
        $statistics = [
            'total_members' => count($members),
            'active_members' => 0,
            'inactive_members' => 0,
            'male_members' => 0,
            'female_members' => 0,
            'voice_parts' => [],
            'age_groups' => [
                'under_18' => 0,
                '18_30' => 0,
                '31_50' => 0,
                'over_50' => 0
            ]
        ];

        // Count statistics
        foreach ($members as $member) {
            // Status count
            if ($member['membership_status'] === 'Active') {
                $statistics['active_members']++;
            } else {
                $statistics['inactive_members']++;
            }
            
            // Gender count
            if ($member['sex'] === 'Male') {
                $statistics['male_members']++;
            } elseif ($member['sex'] === 'Female') {
                $statistics['female_members']++;
            }
            
            // Voice parts count
            $voicePart = $member['voice_part'] ?? 'Not Specified';
            if (!isset($statistics['voice_parts'][$voicePart])) {
                $statistics['voice_parts'][$voicePart] = 0;
            }
            $statistics['voice_parts'][$voicePart]++;
            
            // Age groups (if date_of_birth is available)
            if (!empty($member['date_of_birth'])) {
                $birthDate = new DateTime($member['date_of_birth']);
                $today = new DateTime();
                $age = $today->diff($birthDate)->y;
                
                if ($age < 18) {
                    $statistics['age_groups']['under_18']++;
                } elseif ($age <= 30) {
                    $statistics['age_groups']['18_30']++;
                } elseif ($age <= 50) {
                    $statistics['age_groups']['31_50']++;
                } else {
                    $statistics['age_groups']['over_50']++;
                }
            }
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $society ? htmlspecialchars($society['name']) . ' - Society Details' : 'Society Details'; ?> - GHAMECC</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-users me-2"></i>
                        <?php echo $society ? htmlspecialchars($society['name']) . ' Society' : 'Society Details'; ?>
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="index.php" class="btn btn-sm btn-outline-secondary me-2">
                            <i class="fas fa-arrow-left"></i> Back to Societies
                        </a>
                        <?php if ($society && ($userRole === 'admin' || $userRole === 'society_secretary')): ?>
                            <a href="../members/register.php?society_id=<?php echo $society['id']; ?>" class="btn btn-sm btn-primary">
                                <i class="fas fa-user-plus"></i> Add Member
                            </a>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if ($society): ?>
                    <!-- Society Information Card -->
                    <div class="row mb-4">
                        <div class="col-lg-8">
                            <div class="card shadow">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-info-circle me-2"></i>Society Information
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <table class="table table-borderless">
                                                <tr>
                                                    <td><strong>Society Name:</strong></td>
                                                    <td><?php echo htmlspecialchars($society['name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Society Code:</strong></td>
                                                    <td><span class="badge bg-primary"><?php echo htmlspecialchars($society['code'] ?? 'N/A'); ?></span></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Circuit:</strong></td>
                                                    <td>
                                                        <a href="../circuits/view.php?id=<?php echo $society['circuit_id']; ?>">
                                                            <?php echo htmlspecialchars($society['circuit_name']); ?>
                                                        </a>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Diocese:</strong></td>
                                                    <td><?php echo htmlspecialchars($society['diocese_name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Location:</strong></td>
                                                    <td><?php echo htmlspecialchars($society['address'] ?? 'Not specified'); ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                        <div class="col-md-6">
                                            <table class="table table-borderless">
                                                <tr>
                                                    <td><strong>Contact Person:</strong></td>
                                                    <td><?php echo htmlspecialchars($society['contact_person'] ?? 'Not specified'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Secretary:</strong></td>
                                                    <td><?php echo htmlspecialchars($society['secretary'] ?? 'Not specified'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Contact Phone:</strong></td>
                                                    <td>
                                                        <?php if (!empty($society['contact_phone'])): ?>
                                                            <a href="tel:<?php echo htmlspecialchars($society['contact_phone']); ?>">
                                                                <?php echo htmlspecialchars($society['contact_phone']); ?>
                                                            </a>
                                                        <?php else: ?>
                                                            Not specified
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Contact Email:</strong></td>
                                                    <td>
                                                        <?php if (!empty($society['contact_email'])): ?>
                                                            <a href="mailto:<?php echo htmlspecialchars($society['contact_email']); ?>">
                                                                <?php echo htmlspecialchars($society['contact_email']); ?>
                                                            </a>
                                                        <?php else: ?>
                                                            Not specified
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Established:</strong></td>
                                                    <td><?php echo !empty($society['established']) ? htmlspecialchars($society['established']) : 'Not specified'; ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                    <?php if (!empty($society['description'])): ?>
                                        <div class="row mt-3">
                                            <div class="col-12">
                                                <strong>Description:</strong>
                                                <p class="mt-2"><?php echo nl2br(htmlspecialchars($society['description'])); ?></p>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Statistics Card -->
                        <div class="col-lg-4">
                            <div class="card shadow">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-chart-bar me-2"></i>Statistics
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="row text-center">
                                        <div class="col-6 mb-3">
                                            <div class="card bg-primary text-white">
                                                <div class="card-body">
                                                    <h4><?php echo $statistics['total_members']; ?></h4>
                                                    <small>Total Members</small>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-6 mb-3">
                                            <div class="card bg-success text-white">
                                                <div class="card-body">
                                                    <h4><?php echo $statistics['active_members']; ?></h4>
                                                    <small>Active</small>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="card bg-info text-white">
                                                <div class="card-body">
                                                    <h4><?php echo $statistics['male_members']; ?></h4>
                                                    <small>Male</small>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <div class="card bg-warning text-white">
                                                <div class="card-body">
                                                    <h4><?php echo $statistics['female_members']; ?></h4>
                                                    <small>Female</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Society Members -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card shadow">
                                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-user-friends me-2"></i>Society Members
                                    </h6>
                                    <span class="badge bg-primary"><?php echo count($members); ?> members</span>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($members)): ?>
                                        <div class="alert alert-info">
                                            <i class="fas fa-info-circle me-2"></i>No members found in this society.
                                            <?php if ($userRole === 'admin' || $userRole === 'society_secretary'): ?>
                                                <a href="../members/register.php?society_id=<?php echo $society['id']; ?>" class="btn btn-sm btn-primary ms-2">
                                                    <i class="fas fa-user-plus"></i> Add First Member
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-bordered" id="membersTable">
                                                <thead>
                                                    <tr>
                                                        <th style="width:60px">Photo</th>
                                                        <th>Name</th>
                                                        <th>Gender</th>
                                                        <th>Voice Part</th>
                                                        <th>Status</th>
                                                        <th>Contact</th>
                                                        <th>Email</th>
                                                        <th>Position</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($members as $member): ?>
                                                        <tr>
                                                            <td>
                                                                <?php
                                                                $initials = '';
                                                                if (!empty($member['first_name']) || !empty($member['last_name'])) {
                                                                    $initials = strtoupper(substr($member['first_name'] ?? '', 0, 1) . substr($member['last_name'] ?? '', 0, 1));
                                                                }
                                                                if (!empty($member['profile_image'])) {
                                                                    echo '<img src="../uploads/members/' . htmlspecialchars($member['profile_image']) . '" style="width:40px;height:40px;border-radius:50%;object-fit:cover;" />';
                                                                } else {
                                                                    echo '<div style="width:40px;height:40px;border-radius:50%;background:#e9ecef;color:#6c757d;display:flex;align-items:center;justify-content:center;font-weight:600;">' . $initials . '</div>';
                                                                }
                                                                ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($member['first_name'] . ' ' . $member['last_name']); ?></td>
                                                            <td>
                                                                <span class="badge <?php echo $member['sex'] === 'Male' ? 'bg-info' : 'bg-warning'; ?>">
                                                                    <?php echo $member['gender_display']; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if (!empty($member['voice_part'])): ?>
                                                                    <span class="badge bg-secondary"><?php echo htmlspecialchars($member['voice_part']); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Not specified</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <span class="badge <?php 
                                                                    echo $member['membership_status'] === 'Active' ? 'bg-success' : 
                                                                         ($member['membership_status'] === 'Inactive' ? 'bg-secondary' : 'bg-danger'); 
                                                                ?>">
                                                                    <?php echo $member['status_display']; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if (!empty($member['contact_number_1'])): ?>
                                                                    <a href="tel:<?php echo htmlspecialchars($member['contact_number_1']); ?>">
                                                                        <?php echo htmlspecialchars($member['contact_number_1']); ?>
                                                                    </a>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Not provided</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if (!empty($member['email'])): ?>
                                                                    <a href="mailto:<?php echo htmlspecialchars($member['email']); ?>">
                                                                        <?php echo htmlspecialchars($member['email']); ?>
                                                                    </a>
                                                                <?php else: ?>
                                                                    <span class="text-muted">Not provided</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($member['position'] ?? 'Member'); ?></td>
                                                            <td>
                                                                <div class="btn-group btn-group-sm">
                                                                    <a href="../members/view.php?id=<?php echo $member['id']; ?>" class="btn btn-info">
                                                                        <i class="fas fa-eye"></i>
                                                                    </a>
                                                                    <?php if ($userRole === 'admin' || $userRole === 'society_secretary'): ?>
                                                                        <a href="../members/edit.php?id=<?php echo $member['id']; ?>" class="btn btn-primary">
                                                                            <i class="fas fa-edit"></i>
                                                                        </a>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charts Row -->
                    <?php if (!empty($statistics['voice_parts']) || $statistics['total_members'] > 0): ?>
                    <div class="row">
                        <?php if (!empty($statistics['voice_parts'])): ?>
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-music me-2"></i>Voice Parts Distribution
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container" style="height: 300px;">
                                        <canvas id="voicePartsChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($statistics['total_members'] > 0): ?>
                        <div class="col-lg-6 mb-4">
                            <div class="card shadow">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-venus-mars me-2"></i>Gender & Status Distribution
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container" style="height: 300px;">
                                        <canvas id="genderStatusChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize DataTable
        $('#membersTable').DataTable({
            order: [[0, 'asc']],
            pageLength: 25,
            columnDefs: [
                { orderable: false, targets: -1 } // Disable sorting on Actions column
            ]
        });
        
        <?php if (!empty($statistics['voice_parts'])): ?>
        // Voice Parts Chart
        const voicePartsCtx = document.getElementById('voicePartsChart').getContext('2d');
        new Chart(voicePartsCtx, {
            type: 'doughnut',
            data: {
                labels: <?php echo json_encode(array_keys($statistics['voice_parts'])); ?>,
                datasets: [{
                    data: <?php echo json_encode(array_values($statistics['voice_parts'])); ?>,
                    backgroundColor: [
                        '#FF6384',
                        '#36A2EB',
                        '#FFCE56',
                        '#4BC0C0',
                        '#9966FF',
                        '#FF9F40',
                        '#FF6384',
                        '#C9CBCF'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
        <?php endif; ?>
        
        <?php if ($statistics['total_members'] > 0): ?>
        // Gender & Status Chart
        const genderStatusCtx = document.getElementById('genderStatusChart').getContext('2d');
        new Chart(genderStatusCtx, {
            type: 'bar',
            data: {
                labels: ['Male', 'Female', 'Active', 'Inactive'],
                datasets: [{
                    label: 'Count',
                    data: [
                        <?php echo $statistics['male_members']; ?>, 
                        <?php echo $statistics['female_members']; ?>,
                        <?php echo $statistics['active_members']; ?>,
                        <?php echo $statistics['inactive_members']; ?>
                    ],
                    backgroundColor: [
                        '#36A2EB',
                        '#FF6384',
                        '#4BC0C0',
                        '#FFCE56'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
        <?php endif; ?>
    });
    </script>
</body>
</html>
