<?php
/**
 * Admin Dioceses Management
 * GHAMECC Choir Management Platform
 */

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

// Require login and admin role
requireLogin();
requireRole('admin');

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

// Get user information
$userId = $_SESSION['user_id'];
$userFullName = $_SESSION['full_name'] ?? $_SESSION['username'];
$userRole = $_SESSION['role'] ?? '';

// Initialize variables
$dioceses = [];
$message = '';
$error = '';

// Process form submission for creating a new diocese
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_diocese'])) {
    $name = trim($_POST['name'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $connexionId = (int)($_POST['connexion_id'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $chairmanName = trim($_POST['chairman_name'] ?? '');
    $secretaryName = trim($_POST['secretary_name'] ?? '');
    $contactEmail = trim($_POST['contact_email'] ?? '');
    $contactPhone = trim($_POST['contact_phone'] ?? '');
    $established = trim($_POST['established'] ?? '');
    
    // Validate input
    if (empty($name) || empty($code) || $connexionId <= 0) {
        $error = "Name, code, and connexion are required fields.";
    } else {
        // Check if diocese code already exists
        $existingDiocese = fetchRow("SELECT id FROM dioceses WHERE code = ?", [$code]);
        
        if ($existingDiocese) {
            $error = "Diocese with code '$code' already exists.";
        } else {
            // Insert new diocese
            $query = "INSERT INTO dioceses (name, code, connexion_id, description, address, chairman_name, secretary_name, contact_email, contact_phone, established, created_by) 
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $result = executeQuery($query, [
                $name, $code, $connexionId, $description, $address, 
                $chairmanName, $secretaryName, $contactEmail, $contactPhone, 
                $established, $userId
            ]);
            
            if ($result) {
                $message = "Diocese created successfully.";
                // Redirect to prevent form resubmission
                header("Location: dioceses.php");
                exit;
            } else {
                $error = "Failed to create diocese. Please try again.";
            }
        }
    }
}

// Process form submission for editing a diocese
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_diocese'])) {
    $dioceseId = (int)($_POST['diocese_id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $code = trim($_POST['code'] ?? '');
    $connexionId = (int)($_POST['connexion_id'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $chairmanName = trim($_POST['chairman_name'] ?? '');
    $secretaryName = trim($_POST['secretary_name'] ?? '');
    $contactEmail = trim($_POST['contact_email'] ?? '');
    $contactPhone = trim($_POST['contact_phone'] ?? '');
    $established = trim($_POST['established'] ?? '');
    
    // Validate input
    if (empty($name) || empty($code) || $connexionId <= 0 || $dioceseId <= 0) {
        $error = "Name, code, and connexion are required fields.";
    } else {
        // Check if diocese code already exists for another diocese
        $existingDiocese = fetchRow("SELECT id FROM dioceses WHERE code = ? AND id != ?", [$code, $dioceseId]);
        
        if ($existingDiocese) {
            $error = "Diocese with code '$code' already exists.";
        } else {
            // Update diocese
            $query = "UPDATE dioceses SET 
                      name = ?, 
                      code = ?, 
                      connexion_id = ?, 
                      description = ?, 
                      address = ?, 
                      chairman_name = ?, 
                      secretary_name = ?, 
                      contact_email = ?, 
                      contact_phone = ?, 
                      established = ? 
                      WHERE id = ?";
            
            $result = executeQuery($query, [
                $name, $code, $connexionId, $description, $address, 
                $chairmanName, $secretaryName, $contactEmail, $contactPhone, 
                $established, $dioceseId
            ]);
            
            if ($result !== false) {
                $message = "Diocese updated successfully.";
                // Redirect to prevent form resubmission
                header("Location: dioceses.php");
                exit;
            } else {
                $error = "Failed to update diocese. Please try again.";
            }
        }
    }
}

// Process form submission for deleting a diocese
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_diocese'])) {
    $dioceseId = (int)($_POST['diocese_id'] ?? 0);
    
    if ($dioceseId <= 0) {
        $error = "Invalid diocese ID.";
    } else {
        // Check if there are circuits associated with this diocese
        $circuits = fetchRows("SELECT id FROM circuits WHERE diocese_id = ?", [$dioceseId]);
        
        if (!empty($circuits)) {
            $error = "Cannot delete diocese because it has associated circuits. Please delete or reassign the circuits first.";
        } else {
            // Delete diocese
            $result = executeQuery("DELETE FROM dioceses WHERE id = ?", [$dioceseId]);
            
            if ($result) {
                $message = "Diocese deleted successfully.";
                // Redirect to prevent form resubmission
                header("Location: dioceses.php");
                exit;
            } else {
                $error = "Failed to delete diocese. Please try again.";
            }
        }
    }
}

// Get all dioceses
$dioceses = fetchRows("SELECT d.*, c.name as connexion_name 
                      FROM dioceses d 
                      LEFT JOIN connexion c ON d.connexion_id = c.id 
                      ORDER BY d.name");

// Get all connexions for the dropdown
$connexions = fetchRows("SELECT id, name FROM connexion ORDER BY name");

// Get diocese to edit if in edit mode
$editDiocese = null;
if (isset($_GET['edit'])) {
    $dioceseId = (int)$_GET['edit'];
    if ($dioceseId > 0) {
        $editDiocese = fetchRow("SELECT * FROM dioceses WHERE id = ?", [$dioceseId]);
        
        if (!$editDiocese) {
            $error = "Diocese not found.";
        }
    }
}

// Count total dioceses
$totalDioceses = count($dioceses);

// Count circuits by diocese
$dioceseCircuitCounts = [];
foreach ($dioceses as $diocese) {
    $circuits = fetchRows("SELECT id FROM circuits WHERE diocese_id = ?", [$diocese['id']]);
    $dioceseCircuitCounts[$diocese['id']] = count($circuits);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Diocese Management - GHAMECC Choir Management</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">
    <!-- 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"><?php echo $pageTitle; ?></h1>
                    <?php if ($userRole === 'admin' && !isset($_GET['create']) && !isset($_GET['edit'])): ?>
                        <a href="?create=1" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>Add New Diocese
                        </a>
                    <?php endif; ?>
                </div>
                
                <?php if (!empty($message)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <?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; ?>
                
                <div class="row">
                    <?php if (isset($_GET['create']) || isset($_GET['edit'])): ?>
                    <!-- Create/Edit Diocese Card -->
                    <div class="col-xl-12 col-lg-12 col-md-12 mb-4">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">
                                    <?php echo isset($_GET['edit']) ? 'Edit Diocese' : 'Create New Diocese'; ?>
                                </h6>
                            </div>
                            <div class="card-body">
                                <?php if ($userRole === 'admin' && !empty($connexions)): ?>
                                    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                                        <?php if (isset($_GET['edit'])): ?>
                                            <input type="hidden" name="diocese_id" value="<?php echo $editDiocese['id']; ?>">
                                            <input type="hidden" name="edit_diocese" value="1">
                                        <?php else: ?>
                                            <input type="hidden" name="create_diocese" value="1">
                                        <?php endif; ?>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="name" class="form-label">Diocese Name</label>
                                                <input type="text" class="form-control" id="name" name="name" required
                                                    value="<?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['name']) : ''; ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="code" class="form-label">Diocese Code</label>
                                                <input type="text" class="form-control" id="code" name="code" required
                                                    value="<?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['code']) : ''; ?>">
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="connexion_id" class="form-label">Connexion</label>
                                            <select class="form-select" id="connexion_id" name="connexion_id" required>
                                                <option value="">Select Connexion</option>
                                                <?php foreach ($connexions as $connexion): ?>
                                                <option value="<?php echo $connexion['id']; ?>" <?php echo (isset($editDiocese) && $editDiocese['connexion_id'] == $connexion['id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($connexion['name']); ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="description" class="form-label">Description</label>
                                            <textarea class="form-control" id="description" name="description" rows="3"><?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['description'] ?? '') : ''; ?></textarea>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="address" class="form-label">Address</label>
                                            <textarea class="form-control" id="address" name="address" rows="2"><?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['address'] ?? '') : ''; ?></textarea>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="chairman_name" class="form-label">Chairman Name</label>
                                                <input type="text" class="form-control" id="chairman_name" name="chairman_name"
                                                    value="<?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['chairman_name'] ?? '') : ''; ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="secretary_name" class="form-label">Secretary Name</label>
                                                <input type="text" class="form-control" id="secretary_name" name="secretary_name"
                                                    value="<?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['secretary_name'] ?? '') : ''; ?>">
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="contact_email" class="form-label">Contact Email</label>
                                                <input type="email" class="form-control" id="contact_email" name="contact_email"
                                                    value="<?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['contact_email'] ?? '') : ''; ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="contact_phone" class="form-label">Contact Phone</label>
                                                <input type="text" class="form-control" id="contact_phone" name="contact_phone"
                                                    value="<?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['contact_phone'] ?? '') : ''; ?>">
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="established" class="form-label">Established Date</label>
                                            <input type="date" class="form-control" id="established" name="established"
                                                value="<?php echo isset($editDiocese) ? htmlspecialchars($editDiocese['established'] ?? '') : ''; ?>">
                                        </div>
                                        
                                        <div class="d-flex justify-content-between">
                                            <a href="dioceses.php" class="btn btn-secondary">Cancel</a>
                                            <button type="submit" class="btn btn-primary">
                                                <?php echo isset($_GET['edit']) ? 'Update Diocese' : 'Create Diocese'; ?>
                                            </button>
                                        </div>
                                    </form>
                                <?php elseif (empty($connexions)): ?>
                                    <div class="alert alert-info">
                                        No connexions available. Please create a connexion first.
                                    </div>
                                <?php else: ?>
                                    <div class="alert alert-danger">
                                        You don't have permission to perform this action.
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php else: ?>
                    <!-- Dioceses List Card -->
                    <div class="col-12">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Dioceses List</h6>
                            </div>
                            <div class="card-body">
                                <?php if (empty($dioceses)): ?>
                                    <div class="alert alert-info">
                                        No dioceses found.
                                        <?php if ($userRole === 'admin'): ?>
                                            <a href="?create=1" class="alert-link">Create a new diocese</a>.
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-bordered" id="diocesesTable" width="100%" cellspacing="0">
                                            <thead>
                                                <tr>
                                                    <th>Name</th>
                                                    <th>Code</th>
                                                    <th>Connexion</th>
                                                    <th>Address</th>
                                                    <th>Chairman</th>
                                                    <th>Secretary</th>
                                                    <th>Contact</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($dioceses as $diocese): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($diocese['name']); ?></td>
                                                        <td><?php echo htmlspecialchars($diocese['code']); ?></td>
                                                        <td><?php echo htmlspecialchars($diocese['connexion_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($diocese['address'] ?? ''); ?></td>
                                                        <td><?php echo htmlspecialchars($diocese['chairman_name'] ?? ''); ?></td>
                                                        <td><?php echo htmlspecialchars($diocese['secretary_name'] ?? ''); ?></td>
                                                        <td>
                                                            <?php if (!empty($diocese['contact_email'])): ?>
                                                                <a href="mailto:<?php echo htmlspecialchars($diocese['contact_email']); ?>"><?php echo htmlspecialchars($diocese['contact_email']); ?></a><br>
                                                            <?php endif; ?>
                                                            <?php if (!empty($diocese['contact_phone'])): ?>
                                                                <a href="tel:<?php echo htmlspecialchars($diocese['contact_phone']); ?>"><?php echo htmlspecialchars($diocese['contact_phone']); ?></a>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group btn-group-sm">
                                                                <a href="view.php?id=<?php echo $diocese['id']; ?>" class="btn btn-info">
                                                                    <i class="fas fa-eye"></i>
                                                                </a>
                                                                <?php if ($userRole === 'admin'): ?>
                                                                    <a href="?edit=<?php echo $diocese['id']; ?>" class="btn btn-primary">
                                                                        <i class="fas fa-edit"></i>
                                                                    </a>
                                                                    <button type="button" class="btn btn-danger delete-diocese" 
                                                                            data-id="<?php echo $diocese['id']; ?>"
                                                                            data-name="<?php echo htmlspecialchars($diocese['name']); ?>"
                                                                            data-bs-toggle="modal" data-bs-target="#deleteDioceseModal">
                                                                        <i class="fas fa-trash"></i>
                                                                    </button>
                                                                <?php endif; ?>
                                                                <a href="../circuits/index.php?diocese_id=<?php echo $diocese['id']; ?>" class="btn btn-secondary">
                                                                    <i class="fas fa-sitemap"></i>
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Diocese Statistics Row -->
                <?php if (!isset($_GET['create']) && !isset($_GET['edit'])): ?>
                <div class="row">
                    <div class="col-xl-12 col-lg-12">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Diocese Statistics</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <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">Total Dioceses</div>
                                                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo count($dioceses); ?></div>
                                                    </div>
                                                    <div class="col-auto">
                                                        <i class="fas fa-church fa-2x text-gray-300"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <!-- Delete Diocese Modal -->
    <div class="modal fade" id="deleteDioceseModal" tabindex="-1" aria-labelledby="deleteDioceseModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteDioceseModalLabel">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete diocese <span id="delete_diocese_name"></span>?</p>
                    <p class="text-danger">This action cannot be undone. All circuits and societies under this diocese must be deleted or reassigned first.</p>
                </div>
                <div class="modal-footer">
                    <form method="post" action="">
                        <input type="hidden" name="diocese_id" id="delete_diocese_id">
                        <input type="hidden" name="delete_diocese" value="1">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Delete Diocese</button>
                    </form>
                </div>
            </div>
        </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).ready(function() {
            // Initialize DataTable
            $('#diocesesTable').DataTable({
                order: [[0, 'asc']]
            });
            
            // Handle delete diocese modal
            $('.delete-diocese').click(function() {
                const id = $(this).data('id');
                const name = $(this).data('name');
                
                $('#delete_diocese_id').val(id);
                $('#delete_diocese_name').text(name);
            });
        });
    </script>
</body>
</html>
