<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Check if user has permission to add contributors (Admin or Fund Manager)
if (!in_array($role_name, ['Administrator', 'Fund Manager'])) {
    header('Location: index.php');
    exit();
}

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $middle_name = trim($_POST['middle_name']);
    $email = trim($_POST['email']);
    $phone_primary = trim($_POST['phone_primary']);
    $phone_secondary = trim($_POST['phone_secondary']);
    $relationship = $_POST['relationship'];
    $relationship_details = trim($_POST['relationship_details']);
    $address = trim($_POST['address']);
    $city = trim($_POST['city']);
    $country = $_POST['country'];
    $id_number = trim($_POST['id_number']);
    $date_of_birth = !empty($_POST['date_of_birth']) ? $_POST['date_of_birth'] : null;
    $occupation = trim($_POST['occupation']);
    $bank_name = trim($_POST['bank_name']);
    $bank_account = trim($_POST['bank_account']);
    $mpesa_number = trim($_POST['mpesa_number']);
    $preferred_contact = $_POST['preferred_contact'];
    $trust_level = $_POST['trust_level'];
    $notes = trim($_POST['notes']);
    
    // Validation
    $errors = [];
    
    if (empty($first_name)) {
        $errors[] = "First name is required";
    }
    
    if (empty($last_name)) {
        $errors[] = "Last name is required";
    }
    
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    if (!empty($email)) {
        // Check if email already exists
        $check_email = $conn->prepare("SELECT contributor_id FROM contributors WHERE email = ? AND is_active = 1");
        $check_email->bind_param("s", $email);
        $check_email->execute();
        if ($check_email->get_result()->num_rows > 0) {
            $errors[] = "Email already exists";
        }
    }
    
    if (!empty($phone_primary)) {
        // Check if phone number already exists
        $check_phone = $conn->prepare("SELECT contributor_id FROM contributors WHERE phone_primary = ? AND is_active = 1");
        $check_phone->bind_param("s", $phone_primary);
        $check_phone->execute();
        if ($check_phone->get_result()->num_rows > 0) {
            $errors[] = "Phone number already exists";
        }
    }
    
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            // Insert contributor - the trigger will generate contributor_number automatically
            $insert_query = "INSERT INTO contributors (
                first_name, last_name, middle_name, email, phone_primary, phone_secondary,
                relationship, relationship_details, address, city, country, id_number,
                date_of_birth, occupation, bank_name, bank_account, mpesa_number,
                preferred_contact, trust_level, notes
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($insert_query);
            $stmt->bind_param("ssssssssssssssssssss", 
                $first_name, $last_name, $middle_name, $email, $phone_primary, $phone_secondary,
                $relationship, $relationship_details, $address, $city, $country, $id_number,
                $date_of_birth, $occupation, $bank_name, $bank_account, $mpesa_number,
                $preferred_contact, $trust_level, $notes
            );
            
            if ($stmt->execute()) {
                // FIXED: Get insert_id from connection, not from statement
                $contributor_id = $conn->insert_id;
                
                // Log activity
                $activity_query = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address) 
                                   VALUES (?, 'CREATE', 'CONTRIBUTORS', ?, 'CONTRIBUTOR', ?, ?)";
                $activity_stmt = $conn->prepare($activity_query);
                $new_values = json_encode([
                    'first_name' => $first_name,
                    'last_name' => $last_name,
                    'email' => $email,
                    'phone_primary' => $phone_primary,
                    'relationship' => $relationship
                ]);
                $ip_address = $_SERVER['REMOTE_ADDR'];
                $activity_stmt->bind_param("iiss", $user_id, $contributor_id, $new_values, $ip_address);
                $activity_stmt->execute();
                
                $conn->commit();
                
                $message = "Contributor '$first_name $last_name' added successfully!";
                $message_type = "success";
                
                // Clear form data on success
                $_POST = [];
                
            } else {
                throw new Exception("Error adding contributor: " . $conn->error);
            }
            
        } catch (Exception $e) {
            $conn->rollback();
            $message = "Error: " . $e->getMessage();
            $message_type = "error";
        }
    } else {
        $message = implode(", ", $errors);
        $message_type = "error";
    }
}

// Get statistics for display
$stats_query = "SELECT 
    COUNT(*) as total_contributors,
    COUNT(CASE WHEN trust_level = 'HIGH' THEN 1 END) as high_trust,
    SUM(total_contributed) as total_contributions,
    COUNT(CASE WHEN created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as new_this_month
    FROM contributors 
    WHERE is_active = 1";
$stats = $conn->query($stats_query)->fetch_assoc();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Contributor - Personal Fund Tracker')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from create_fund.php */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Breadcrumb */
        .breadcrumb-card {
            background: white;
            border-radius: 8px;
            padding: 1rem 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .breadcrumb {
            margin: 0;
            background: none;
            padding: 0;
        }
        
        .breadcrumb-item a {
            color: #3b82f6;
            text-decoration: none;
        }
        
        .breadcrumb-item.active {
            color: #64748b;
        }
        
        /* Alert Messages */
        .alert {
            border-radius: 8px;
            border: none;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        /* Form Card */
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .form-section {
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .section-title i {
            color: #059669;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select, .form-control:focus, .form-select:focus {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .form-text {
            color: #64748b;
            font-size: 0.75rem;
            margin-top: 0.25rem;
        }
        
        /* Required field indicator */
        .required {
            color: #dc2626;
        }
        
        /* Buttons */
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-success {
            background: #059669;
            color: white;
        }
        
        .btn-success:hover {
            background: #047857;
            color: white;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
        }
        
        /* Button Group */
        .button-group {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            padding-top: 1.5rem;
            border-top: 1px solid #e2e8f0;
            margin-top: 2rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .button-group {
                flex-direction: column;
            }
            
            .form-card {
                padding: 1.5rem;
            }
        }
        
        /* Footer spacing fix */
        .main-content {
            padding-bottom: 2rem;
        }
        
        .page-content {
            margin-bottom: 3rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Add New Contributor</h1>
                        <p class="page-subtitle">Register a new contributor to the fund management system</p>
                    </div>

                    <!-- Breadcrumb -->
                    <div class="breadcrumb-card">
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                <li class="breadcrumb-item"><a href="list_contributors.php">All Contributors</a></li>
                                <li class="breadcrumb-item active">Add Contributor</li>
                            </ol>
                        </nav>
                    </div>

                    <!-- Alert Messages - Remove this section since we're using SweetAlert -->
                    <?php 
                    // We'll handle messages with SweetAlert instead of HTML alerts
                    ?>

                    <!-- Current System Stats -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_contributors'] ?? 0; ?></div>
                            <div class="stat-label">Total Contributors</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['high_trust'] ?? 0; ?></div>
                            <div class="stat-label">High Trust Level</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($stats['total_contributions'] ?? 0); ?></div>
                            <div class="stat-label">Total Contributions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['new_this_month'] ?? 0; ?></div>
                            <div class="stat-label">New This Month</div>
                        </div>
                    </div>

                    <!-- Add Contributor Form -->
                    <div class="form-card">
                        <h3 class="form-title">Contributor Information</h3>
                        
                        <form method="POST" id="addContributorForm">
                            <!-- Personal Information Section -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-user"></i>
                                    Personal Information
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">First Name <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="first_name" required 
                                               placeholder="John" 
                                               value="<?php echo htmlspecialchars($_POST['first_name'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <label class="form-label">Last Name <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="last_name" required 
                                               placeholder="Doe" 
                                               value="<?php echo htmlspecialchars($_POST['last_name'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <label class="form-label">Middle Name</label>
                                        <input type="text" class="form-control" name="middle_name" 
                                               placeholder="Optional" 
                                               value="<?php echo htmlspecialchars($_POST['middle_name'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Date of Birth</label>
                                        <input type="date" class="form-control" name="date_of_birth" 
                                               value="<?php echo htmlspecialchars($_POST['date_of_birth'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">ID Number</label>
                                        <input type="text" class="form-control" name="id_number" 
                                               placeholder="National ID or Passport" 
                                               value="<?php echo htmlspecialchars($_POST['id_number'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Occupation</label>
                                        <input type="text" class="form-control" name="occupation" 
                                               placeholder="e.g., Teacher, Engineer" 
                                               value="<?php echo htmlspecialchars($_POST['occupation'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Trust Level</label>
                                        <select class="form-select" name="trust_level">
                                            <option value="MEDIUM" <?php echo (($_POST['trust_level'] ?? 'MEDIUM') == 'MEDIUM') ? 'selected' : ''; ?>>Medium</option>
                                            <option value="HIGH" <?php echo (($_POST['trust_level'] ?? '') == 'HIGH') ? 'selected' : ''; ?>>High</option>
                                            <option value="LOW" <?php echo (($_POST['trust_level'] ?? '') == 'LOW') ? 'selected' : ''; ?>>Low</option>
                                        </select>
                                        <div class="form-text">Assessment of contributor reliability</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Contact Information Section -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-phone"></i>
                                    Contact Information
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Primary Phone</label>
                                        <input type="tel" class="form-control" name="phone_primary" 
                                               placeholder="+254700000000" 
                                               value="<?php echo htmlspecialchars($_POST['phone_primary'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Secondary Phone</label>
                                        <input type="tel" class="form-control" name="phone_secondary" 
                                               placeholder="+254700000000" 
                                               value="<?php echo htmlspecialchars($_POST['phone_secondary'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Email Address</label>
                                        <input type="email" class="form-control" name="email" 
                                               placeholder="john.doe@example.com" 
                                               value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Preferred Contact Method</label>
                                        <select class="form-select" name="preferred_contact">
                                            <option value="PHONE" <?php echo (($_POST['preferred_contact'] ?? 'PHONE') == 'PHONE') ? 'selected' : ''; ?>>Phone</option>
                                            <option value="SMS" <?php echo (($_POST['preferred_contact'] ?? '') == 'SMS') ? 'selected' : ''; ?>>SMS</option>
                                            <option value="EMAIL" <?php echo (($_POST['preferred_contact'] ?? '') == 'EMAIL') ? 'selected' : ''; ?>>Email</option>
                                            <option value="WHATSAPP" <?php echo (($_POST['preferred_contact'] ?? '') == 'WHATSAPP') ? 'selected' : ''; ?>>WhatsApp</option>
                                        </select>
                                    </div>
                                    
                                    <div class="col-12">
                                        <label class="form-label">Address</label>
                                        <textarea class="form-control" name="address" rows="2" 
                                                  placeholder="Street address, P.O. Box, etc."><?php echo htmlspecialchars($_POST['address'] ?? ''); ?></textarea>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">City</label>
                                        <input type="text" class="form-control" name="city" 
                                               placeholder="Nairobi" 
                                               value="<?php echo htmlspecialchars($_POST['city'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Country</label>
                                        <select class="form-select" name="country">
                                            <option value="Kenya" <?php echo (($_POST['country'] ?? 'Kenya') == 'Kenya') ? 'selected' : ''; ?>>Kenya</option>
                                            <option value="Uganda" <?php echo (($_POST['country'] ?? '') == 'Uganda') ? 'selected' : ''; ?>>Uganda</option>
                                            <option value="Tanzania" <?php echo (($_POST['country'] ?? '') == 'Tanzania') ? 'selected' : ''; ?>>Tanzania</option>
                                            <option value="Rwanda" <?php echo (($_POST['country'] ?? '') == 'Rwanda') ? 'selected' : ''; ?>>Rwanda</option>
                                            <option value="Other" <?php echo (($_POST['country'] ?? '') == 'Other') ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Relationship & Financial Section -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-heart"></i>
                                    Relationship & Financial Details
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Relationship</label>
                                        <select class="form-select" name="relationship">
                                            <option value="OTHER" <?php echo (($_POST['relationship'] ?? 'OTHER') == 'OTHER') ? 'selected' : ''; ?>>Other</option>
                                            <option value="FAMILY" <?php echo (($_POST['relationship'] ?? '') == 'FAMILY') ? 'selected' : ''; ?>>Family</option>
                                            <option value="FRIEND" <?php echo (($_POST['relationship'] ?? '') == 'FRIEND') ? 'selected' : ''; ?>>Friend</option>
                                            <option value="BUSINESS_PARTNER" <?php echo (($_POST['relationship'] ?? '') == 'BUSINESS_PARTNER') ? 'selected' : ''; ?>>Business Partner</option>
                                            <option value="PERSONAL_INVESTOR" <?php echo (($_POST['relationship'] ?? '') == 'PERSONAL_INVESTOR') ? 'selected' : ''; ?>>Personal Investor</option>
                                            <option value="COLLEAGUE" <?php echo (($_POST['relationship'] ?? '') == 'COLLEAGUE') ? 'selected' : ''; ?>>Colleague</option>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Relationship Details</label>
                                        <input type="text" class="form-control" name="relationship_details" 
                                               placeholder="e.g., Brother, Close Friend, Business Partner" 
                                               value="<?php echo htmlspecialchars($_POST['relationship_details'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Bank Name</label>
                                        <input type="text" class="form-control" name="bank_name" 
                                               placeholder="e.g., KCB Bank" 
                                               value="<?php echo htmlspecialchars($_POST['bank_name'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">Bank Account Number</label>
                                        <input type="text" class="form-control" name="bank_account" 
                                               placeholder="Account number" 
                                               value="<?php echo htmlspecialchars($_POST['bank_account'] ?? ''); ?>">
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <label class="form-label">M-Pesa Number</label>
                                        <input type="tel" class="form-control" name="mpesa_number" 
                                               placeholder="+254700000000" 
                                               value="<?php echo htmlspecialchars($_POST['mpesa_number'] ?? ''); ?>">
                                        <div class="form-text">For mobile money transactions</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Additional Notes Section -->
                            <div class="form-section">
                                <h4 class="section-title">
                                    <i class="ph-note"></i>
                                    Additional Notes
                                </h4>
                                
                                <div class="row g-3">
                                    <div class="col-12">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="notes" rows="4" 
                                                  placeholder="Any additional information about the contributor"><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                                        <div class="form-text">Internal notes (not visible to the contributor)</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Buttons -->
                            <div class="button-group">
                                <a href="list_contributors.php" class="btn btn-outline-secondary">
                                    <i class="ph-x"></i> Cancel
                                </a>
                                <button type="submit" class="btn btn-success">
                                    <i class="ph-user-plus"></i> Add Contributor
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Show SweetAlert messages if present
            <?php if ($message): ?>
                Swal.fire({
                    title: '<?php echo $message_type === "success" ? "Success!" : "Error!"; ?>',
                    text: '<?php echo addslashes($message); ?>',
                    icon: '<?php echo $message_type === "success" ? "success" : "error"; ?>',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#059669'
                }).then((result) => {
                    <?php if ($message_type === "success"): ?>
                        // Optionally redirect to contributors list
                        window.location.href = 'list_contributors.php';
                    <?php endif; ?>
                });
            <?php endif; ?>
            
            // Phone number formatting
            $('input[type="tel"]').on('input', function() {
                let value = $(this).val().replace(/\D/g, '');
                if (value.startsWith('254')) {
                    value = '+' + value;
                } else if (value.startsWith('0')) {
                    value = '+254' + value.substring(1);
                } else if (value.length === 9) {
                    value = '+254' + value;
                }
                $(this).val(value);
            });
            
            // Email validation
            $('input[type="email"]').on('blur', function() {
                const email = $(this).val();
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                
                if (email && !emailRegex.test(email)) {
                    $(this).addClass('is-invalid');
                    if (!$(this).next('.invalid-feedback').length) {
                        $(this).after('<div class="invalid-feedback">Please enter a valid email address</div>');
                    }
                } else {
                    $(this).removeClass('is-invalid');
                    $(this).next('.invalid-feedback').remove();
                }
            });
            
            // Form validation
            $('#addContributorForm').on('submit', function(e) {
                e.preventDefault();
                
                let isValid = true;
                let errorMessages = [];
                
                // Check required fields
                $(this).find('input[required]').each(function() {
                    if (!$(this).val().trim()) {
                        $(this).addClass('is-invalid');
                        isValid = false;
                        errorMessages.push($(this).prev('label').text().replace('*', '').trim() + ' is required');
                    } else {
                        $(this).removeClass('is-invalid');
                    }
                });
                
                // Check email format if provided
                const email = $('input[name="email"]').val();
                if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                    $('input[name="email"]').addClass('is-invalid');
                    errorMessages.push('Please enter a valid email address');
                    isValid = false;
                }
                
                if (!isValid) {
                    Swal.fire({
                        title: 'Validation Error!',
                        html: 'Please fix the following issues:<br>• ' + errorMessages.join('<br>• '),
                        icon: 'error',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#dc2626'
                    });
                    return false;
                }
                
                // Show confirmation dialog
                const firstName = $('input[name="first_name"]').val();
                const lastName = $('input[name="last_name"]').val();
                const relationship = $('select[name="relationship"]').val();
                
                Swal.fire({
                    title: 'Confirm Addition',
                    html: `
                        <div style="text-align: left; padding: 1rem;">
                            <p><strong>Name:</strong> ${firstName} ${lastName}</p>
                            <p><strong>Relationship:</strong> ${relationship}</p>
                            <p><strong>Email:</strong> ${email || 'Not provided'}</p>
                            <p><strong>Phone:</strong> ${$('input[name="phone_primary"]').val() || 'Not provided'}</p>
                        </div>
                    `,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Add Contributor',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#059669',
                    cancelButtonColor: '#6b7280'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Show loading
                        Swal.fire({
                            title: 'Adding Contributor...',
                            text: 'Please wait while we add the contributor to the system.',
                            icon: 'info',
                            allowOutsideClick: false,
                            showConfirmButton: false,
                            didOpen: () => {
                                Swal.showLoading();
                            }
                        });
                        
                        // Submit the form
                        this.submit();
                    }
                });
            });
            
            // Auto-fill M-Pesa number from primary phone
            $('input[name="phone_primary"]').on('change', function() {
                const phone = $(this).val();
                const mpesaField = $('input[name="mpesa_number"]');
                
                if (phone && !mpesaField.val()) {
                    mpesaField.val(phone);
                }
            });
            
            // Relationship details show/hide based on relationship type
            $('select[name="relationship"]').on('change', function() {
                const relationshipDetails = $('input[name="relationship_details"]');
                
                if ($(this).val() === 'OTHER') {
                    relationshipDetails.attr('required', true);
                    relationshipDetails.closest('.col-md-6').find('.form-label').html('Relationship Details <span class="required">*</span>');
                } else {
                    relationshipDetails.attr('required', false);
                    relationshipDetails.closest('.col-md-6').find('.form-label').html('Relationship Details');
                }
            });
            
            // Initialize relationship details requirement
            $('select[name="relationship"]').trigger('change');
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>