<?php
/**
 * Member Delete Script
 * GHAMECC Choir Management Platform
 */

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

// Ensure user is logged in
requireLogin();

// Log page access
logMemberInfo("Member delete page accessed", [
    'user_role' => $_SESSION['role'] ?? 'unknown',
    'society_id' => $_SESSION['society_id'] ?? null
]);

// Check if user has permission to delete members
if (!hasRole(['admin', 'manager', 'choirmaster', 'society_secretary', 'society_treasurer'])) {
    // Only admin, manager, and society-level roles can delete members
    header("Location: list.php?error=permission_denied");
    exit;
}

// Initialize variables
$error = '';
$success = false;
$memberId = 0;
$memberName = '';

// Check if member ID is provided
if (isset($_GET['id']) && !empty($_GET['id'])) {
    $memberId = (int)$_GET['id'];
    
    // Get member details before deletion for confirmation
    $member = fetchRows("SELECT id, first_name, last_name, part, membership_status FROM members WHERE id = ?", [$memberId]);
    
    if (empty($member)) {
        header("Location: list.php?error=member_not_found");
        exit;
    }
    
    $memberName = $member[0]['first_name'] . ' ' . $member[0]['last_name'];
    $memberIdCode = $member[0]['id'];
    
    // Check if this is a confirmation request
    if (isset($_POST['confirm_delete']) && $_POST['confirm_delete'] === 'yes') {
        
        // Check if member has related records (simplified check)
        $hasUserAccount = false;
        $hasAttendanceRecords = false;
        $hasFinancialRecords = false;
        
        // Check for user account
        try {
            $userAccount = fetchRows("SELECT id FROM users WHERE member_id = ?", [$memberId]);
            $hasUserAccount = !empty($userAccount);
        } catch (Exception $e) {
            // Table might not exist, continue
        }
        
        // Check for attendance records
        try {
            $attendanceRecords = fetchRows("SELECT COUNT(*) as count FROM attendance WHERE member_id = ?", [$memberId]);
            $hasAttendanceRecords = !empty($attendanceRecords) && $attendanceRecords[0]['count'] > 0;
        } catch (Exception $e) {
            // Table might not exist, continue
        }
        
        // Check for financial records
        try {
            $financialRecords = fetchRows("SELECT COUNT(*) as count FROM financial_records WHERE member_id = ?", [$memberId]);
            $hasFinancialRecords = !empty($financialRecords) && $financialRecords[0]['count'] > 0;
        } catch (Exception $e) {
            // Table might not exist, continue
        }
        
        // If member has related records, we should not delete but deactivate instead
        if ($hasUserAccount || $hasAttendanceRecords || $hasFinancialRecords) {
            // Deactivate the member instead of deleting
            $result = executeQuery("UPDATE members SET membership_status = 'inactive', updated_at = NOW() WHERE id = ?", [$memberId]);
            
            if ($result) {
                // Log member deactivation
                logMemberWarning("Member deactivated instead of deleted due to related records", [
                    'member_id' => $memberId,
                    'member_name' => $memberName,
                    'has_user_account' => $hasUserAccount,
                    'has_attendance_records' => $hasAttendanceRecords,
                    'has_financial_records' => $hasFinancialRecords
                ]);
                
                // Redirect with success message about deactivation
                header("Location: list.php?message=member_deactivated&name=" . urlencode($memberName));
                exit;
            } else {
                $error = "Failed to deactivate member. Please try again.";
                
                // Log deactivation failure
                logMemberError("Failed to deactivate member", [
                    'member_id' => $memberId,
                    'member_name' => $memberName
                ]);
            }
        } else {
            // No related records, safe to delete
            // Check if member has a profile image
            $profileImage = fetchRows("SELECT profile_image FROM members WHERE id = ?", [$memberId]);
            
            // Delete the member
            $result = executeQuery("DELETE FROM members WHERE id = ?", [$memberId]);
            
            if ($result) {
                // Log member deletion
                logMemberInfo("Member deleted successfully", [
                    'member_id' => $memberId,
                    'member_name' => $memberName
                ]);
                
                // Delete profile image if exists
                if (!empty($profileImage) && !empty($profileImage[0]['profile_image'])) {
                    $imagePath = "../uploads/members/" . $profileImage[0]['profile_image'];
                    if (file_exists($imagePath)) {
                        unlink($imagePath);
                        
                        // Log profile image deletion
                        logMemberDebug("Member profile image deleted", [
                            'member_id' => $memberId,
                            'image_path' => $imagePath
                        ]);
                    }
                }
                
                // Redirect with success message
                header("Location: list.php?message=member_deleted&name=" . urlencode($memberName));
                exit;
            } else {
                $error = "Failed to delete member. Please try again.";
                
                // Log deletion failure
                logMemberError("Failed to delete member", [
                    'member_id' => $memberId,
                    'member_name' => $memberName
                ]);
            }
        }
    }
} else {
    header("Location: list.php?error=invalid_id");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete Member - <?php echo htmlspecialchars($memberName); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.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="text-center mb-4">
                    <i class="bi bi-person-x-fill text-danger" style="font-size: 4rem;"></i>
                    <h4 class="mt-3">Are you sure you want to delete this member?</h4>
                    <p class="lead"><?php echo htmlspecialchars($memberName); ?> (<?php echo htmlspecialchars($memberIdCode); ?>)</p>
                    <div class="alert alert-warning">
                        <i class="bi bi-info-circle-fill me-2"></i> This action cannot be undone. If the member has related records (user account, attendance, financial), they will be deactivated instead of deleted.
                    </div>
                </div>
                
                <form action="delete.php?id=<?php echo $memberId; ?>" method="post">
                    <div class="d-flex justify-content-center">
                        <a href="view.php?id=<?php echo $memberId; ?>" class="btn btn-secondary me-3">
                            <i class="bi bi-arrow-left"></i> Cancel
                        </a>
                        <button type="submit" name="confirm_delete" value="yes" class="btn btn-danger">
                            <i class="bi bi-trash"></i> Yes, Delete Member
                        </button>
                    </div>
                </form>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
