<?php
/**
 * Circuit View - Display Circuit 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 = "Circuit 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 circuit ID from URL
$circuitId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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

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

// Check if user has permission to view this circuit
$hasPermission = false;
if ($userRole === 'admin') {
    $hasPermission = true;
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    // Check if circuit belongs to user's diocese
    $query = "SELECT id FROM circuits WHERE id = ? AND diocese_id = ?";
    $stmt = $conn->prepare($query);
    if ($stmt === false) {
        error_log("SQL Prepare Error in circuits/view.php (access check): " . $conn->error);
        $error = "Database error occurred while checking access permissions.";
        $circuit = null;
    } else {
        $stmt->bind_param("ii", $circuitId, $userDioceseId);
        $stmt->execute();
        $result = $stmt->get_result();
        $hasPermission = $result->num_rows > 0;
        $stmt->close();
    }
} elseif ($userRole === 'circuit_secretary' && $userCircuitId != $circuitId) {
    $error = "You don't have permission to view this circuit.";
    $circuit = null;
}

// Fetch circuit details if access is granted
if (empty($error)) {
    $query = "SELECT c.*, d.name as diocese_name, d.id as diocese_id
              FROM circuits c
              JOIN dioceses d ON c.diocese_id = d.id
              WHERE c.id = ?";
    $stmt = $conn->prepare($query);
    if ($stmt === false) {
        error_log("SQL Prepare Error in circuits/view.php (circuit details): " . $conn->error);
        $error = "Database error occurred while fetching circuit details.";
        $circuit = null;
    } else {
        $stmt->bind_param("i", $circuitId);
        $stmt->execute();
        $result = $stmt->get_result();
        $circuit = $result->fetch_assoc();
        $stmt->close();
    }
}

if (!$circuit) {
    $error = "Circuit not found.";
} else {
    // Fetch societies in this circuit
    $query = "SELECT s.*, 
                  (SELECT COUNT(*) FROM members WHERE society_id = s.id) as member_count
                  FROM societies s
                  WHERE s.circuit_id = ?
                  ORDER BY s.name";
    $stmt = $conn->prepare($query);
    if ($stmt === false) {
        error_log("SQL Prepare Error in circuits/view.php (societies): " . $conn->error);
        $error = "Database error occurred while fetching societies.";
        $societies = [];
    } else {
        $stmt->bind_param("i", $circuitId);
        $stmt->execute();
        $result = $stmt->get_result();
        $societies = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }

    // Fetch all members in this circuit
    $query = "SELECT m.*, s.name as society_name, s.code as society_code,
                  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
                  JOIN societies s ON m.society_id = s.id
                  WHERE s.circuit_id = ?
                  ORDER BY s.name, m.last_name, m.first_name";
    $stmt = $conn->prepare($query);
    if ($stmt === false) {
        error_log("SQL Prepare Error in circuits/view.php (members): " . $conn->error);
        $error = "Database error occurred while fetching members.";
        $members = [];
    } else {
        $stmt->bind_param("i", $circuitId);
        $stmt->execute();
        $result = $stmt->get_result();
        $members = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }

    // Calculate statistics
    $statistics = [
        'total_societies' => count($societies),
        'total_members' => count($members),
        'male_members' => 0,
        'female_members' => 0,
        'voice_parts' => []
    ];

    // Count gender distribution
    foreach ($members as $member) {
        if ($member['sex'] === 'Male') {
            $statistics['male_members']++;
        } elseif ($member['sex'] === 'Female') {
            $statistics['female_members']++;
        }
        
        // Count voice parts
        $voicePart = $member['voice_part'] ?? 'Not Specified';
        if (!isset($statistics['voice_parts'][$voicePart])) {
            $statistics['voice_parts'][$voicePart] = 0;
        }
        $statistics['voice_parts'][$voicePart]++;
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $circuit ? htmlspecialchars($circuit['name']) . ' - Circuit Details' : 'Circuit 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-circle-nodes me-2"></i>
                        <?php echo $circuit ? htmlspecialchars($circuit['name']) . ' Circuit' : 'Circuit Details'; ?>
                    </h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="index.php" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Circuits
                        </a>
                    </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 ($circuit): ?>
                    <!-- Circuit 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>Circuit Information
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <table class="table table-borderless">
                                                <tr>
                                                    <td><strong>Circuit Name:</strong></td>
                                                    <td><?php echo htmlspecialchars($circuit['name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Circuit Code:</strong></td>
                                                    <td><span class="badge bg-primary"><?php echo htmlspecialchars($circuit['code']); ?></span></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Diocese:</strong></td>
                                                    <td><?php echo htmlspecialchars($circuit['diocese_name']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Location:</strong></td>
                                                    <td><?php echo htmlspecialchars($circuit['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($circuit['contact_person'] ?? 'Not specified'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Contact Phone:</strong></td>
                                                    <td>
                                                        <?php if (!empty($circuit['contact_phone'])): ?>
                                                            <a href="tel:<?php echo htmlspecialchars($circuit['contact_phone']); ?>">
                                                                <?php echo htmlspecialchars($circuit['contact_phone']); ?>
                                                            </a>
                                                        <?php else: ?>
                                                            Not specified
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Contact Email:</strong></td>
                                                    <td>
                                                        <?php if (!empty($circuit['contact_email'])): ?>
                                                            <a href="mailto:<?php echo htmlspecialchars($circuit['contact_email']); ?>">
                                                                <?php echo htmlspecialchars($circuit['contact_email']); ?>
                                                            </a>
                                                        <?php else: ?>
                                                            Not specified
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Description:</strong></td>
                                                    <td><?php echo htmlspecialchars($circuit['description'] ?? 'Not specified'); ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </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_societies']; ?></h4>
                                                    <small>Societies</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['total_members']; ?></h4>
                                                    <small>Members</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>

                    <!-- Societies in Circuit -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card shadow">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-users me-2"></i>Societies in Circuit
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($societies)): ?>
                                        <div class="alert alert-info">
                                            <i class="fas fa-info-circle me-2"></i>No societies found in this circuit.
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-bordered" id="societiesTable">
                                                <thead>
                                                    <tr>
                                                        <th>Society Name</th>
                                                        <th>Code</th>
                                                        <th>Location</th>
                                                        <th>Members</th>
                                                        <th>Contact</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($societies as $society): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($society['name']); ?></td>
                                                            <td><span class="badge bg-secondary"><?php echo htmlspecialchars($society['code'] ?? 'N/A'); ?></span></td>
                                                            <td><?php echo htmlspecialchars($society['location'] ?? 'Not specified'); ?></td>
                                                            <td>
                                                                <span class="badge bg-primary"><?php echo $society['member_count']; ?></span>
                                                            </td>
                                                            <td>
                                                                <?php if (!empty($society['contact_phone'])): ?>
                                                                    <a href="tel:<?php echo htmlspecialchars($society['contact_phone']); ?>" class="btn btn-sm btn-outline-primary">
                                                                        <i class="fas fa-phone"></i>
                                                                    </a>
                                                                <?php endif; ?>
                                                                <?php if (!empty($society['contact_email'])): ?>
                                                                    <a href="mailto:<?php echo htmlspecialchars($society['contact_email']); ?>" class="btn btn-sm btn-outline-primary">
                                                                        <i class="fas fa-envelope"></i>
                                                                    </a>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <a href="../societies/view.php?id=<?php echo $society['id']; ?>" class="btn btn-sm btn-info">
                                                                    <i class="fas fa-eye"></i> View
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Circuit 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>All Circuit 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 circuit.
                                        </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>Society</th>
                                                        <th>Gender</th>
                                                        <th>Voice Part</th>
                                                        <th>Contact</th>
                                                        <th>Email</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><?php echo htmlspecialchars($member['society_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>
                                                                <?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>
                                                                <a href="../members/view.php?id=<?php echo $member['id']; ?>" class="btn btn-sm btn-info">
                                                                    <i class="fas fa-eye"></i> View
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Voice Parts Distribution Chart -->
                    <?php if (!empty($statistics['voice_parts'])): ?>
                    <div class="row">
                        <div class="col-lg-6">
                            <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>
                        
                        <div class="col-lg-6">
                            <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 Distribution
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container" style="height: 300px;">
                                        <canvas id="genderChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </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 DataTables
        $('#societiesTable').DataTable({
            order: [[0, 'asc']],
            pageLength: 10
        });
        
        $('#membersTable').DataTable({
            order: [[0, 'asc']],
            pageLength: 25
        });
        
        <?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'
                    }
                }
            }
        });
        
        // Gender Chart
        const genderCtx = document.getElementById('genderChart').getContext('2d');
        new Chart(genderCtx, {
            type: 'pie',
            data: {
                labels: ['Male', 'Female'],
                datasets: [{
                    data: [<?php echo $statistics['male_members']; ?>, <?php echo $statistics['female_members']; ?>],
                    backgroundColor: ['#36A2EB', '#FF6384']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
        <?php endif; ?>
    });
    </script>
</body>
</html>
