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

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

$user_id = $_SESSION['user_id'];
$customer_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$success_message = '';
$error_message = '';

if (!$customer_id) {
    header('Location: list_customers.php');
    exit();
}

// Get customer details
$sql = "SELECT * FROM customers WHERE customer_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$customer = $stmt->get_result()->fetch_assoc();

if (!$customer) {
    header('Location: list_customers.php?error=customer_not_found');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Validate required fields
        $required_fields = ['first_name', 'last_name', 'phone_primary'];
        foreach ($required_fields as $field) {
            if (empty(trim($_POST[$field]))) {
                throw new Exception(ucfirst(str_replace('_', ' ', $field)) . ' is required');
            }
        }

        // Sanitize input data
        $first_name = trim($_POST['first_name']);
        $last_name = trim($_POST['last_name']);
        $middle_name = trim($_POST['middle_name']) ?: null;
        $email = trim($_POST['email']) ?: null;
        $phone_primary = trim($_POST['phone_primary']);
        $phone_secondary = trim($_POST['phone_secondary']) ?: null;
        $date_of_birth = $_POST['date_of_birth'] ?: null;
        $gender = $_POST['gender'] ?: null;
        $marital_status = $_POST['marital_status'] ?: null;
        $national_id = trim($_POST['national_id']) ?: null;
        $passport_number = trim($_POST['passport_number']) ?: null;
        $driving_license = trim($_POST['driving_license']) ?: null;
        $occupation = trim($_POST['occupation']) ?: null;
        $employer = trim($_POST['employer']) ?: null;
        $monthly_income = !empty($_POST['monthly_income']) ? (float)$_POST['monthly_income'] : null;
        $customer_type = $_POST['customer_type'] ?: 'INDIVIDUAL';
        $segment_id = !empty($_POST['segment_id']) ? (int)$_POST['segment_id'] : null;
        
        // Address information
        $address_line1 = trim($_POST['address_line1']) ?: null;
        $address_line2 = trim($_POST['address_line2']) ?: null;
        $city = trim($_POST['city']) ?: null;
        $county = trim($_POST['county']) ?: null;
        $postal_code = trim($_POST['postal_code']) ?: null;
        $country = $_POST['country'] ?: 'Kenya';
        
        // Emergency contact
        $emergency_contact_name = trim($_POST['emergency_contact_name']) ?: null;
        $emergency_contact_phone = trim($_POST['emergency_contact_phone']) ?: null;
        $emergency_contact_relationship = trim($_POST['emergency_contact_relationship']) ?: null;
        
        // Additional fields
        $preferred_language = $_POST['preferred_language'] ?: 'en';
        $communication_preference = $_POST['communication_preference'] ?: 'SMS';
        $referral_source = trim($_POST['referral_source']) ?: null;
        $referring_agent_id = !empty($_POST['referring_agent_id']) ? (int)$_POST['referring_agent_id'] : null;

        // Validate email format if provided
        if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception('Invalid email format');
        }

        // Validate phone number format
        if (!preg_match('/^(\+254|254|0)[7-9]\d{8}$/', $phone_primary)) {
            throw new Exception('Invalid primary phone number format');
        }

        // Check for duplicates (excluding current customer)
        if ($email) {
            $check_email_sql = "SELECT customer_id FROM customers WHERE email = ? AND customer_id != ? AND is_active = 1";
            $check_stmt = $conn->prepare($check_email_sql);
            $check_stmt->bind_param("si", $email, $customer_id);
            $check_stmt->execute();
            if ($check_stmt->get_result()->num_rows > 0) {
                throw new Exception('Email address already exists');
            }
            $check_stmt->close();
        }

        $check_phone_sql = "SELECT customer_id FROM customers WHERE phone_primary = ? AND customer_id != ? AND is_active = 1";
        $check_stmt = $conn->prepare($check_phone_sql);
        $check_stmt->bind_param("si", $phone_primary, $customer_id);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception('Phone number already exists');
        }
        $check_stmt->close();

        if ($national_id) {
            $check_id_sql = "SELECT customer_id FROM customers WHERE national_id = ? AND customer_id != ? AND is_active = 1";
            $check_stmt = $conn->prepare($check_id_sql);
            $check_stmt->bind_param("si", $national_id, $customer_id);
            $check_stmt->execute();
            if ($check_stmt->get_result()->num_rows > 0) {
                throw new Exception('National ID already exists');
            }
            $check_stmt->close();
        }

        // Begin transaction
        $conn->begin_transaction();

        // Update customer
        $update_sql = "UPDATE customers SET 
            first_name = ?, last_name = ?, middle_name = ?, email = ?, phone_primary = ?, phone_secondary = ?,
            date_of_birth = ?, gender = ?, marital_status = ?, national_id = ?, passport_number = ?, driving_license = ?,
            occupation = ?, employer = ?, monthly_income = ?, customer_type = ?, segment_id = ?,
            address_line1 = ?, address_line2 = ?, city = ?, county = ?, postal_code = ?, country = ?,
            emergency_contact_name = ?, emergency_contact_phone = ?, emergency_contact_relationship = ?,
            preferred_language = ?, communication_preference = ?, referral_source = ?, referring_agent_id = ?,
            updated_at = NOW()
            WHERE customer_id = ?";

        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ssssssssssssssdsississssssssssii", 
            $first_name, $last_name, $middle_name, $email, $phone_primary, $phone_secondary,
            $date_of_birth, $gender, $marital_status, $national_id, $passport_number, $driving_license,
            $occupation, $employer, $monthly_income, $customer_type, $segment_id,
            $address_line1, $address_line2, $city, $county, $postal_code, $country,
            $emergency_contact_name, $emergency_contact_phone, $emergency_contact_relationship,
            $preferred_language, $communication_preference, $referral_source, $referring_agent_id,
            $customer_id
        );

        if (!$update_stmt->execute()) {
            throw new Exception('Failed to update customer: ' . $update_stmt->error);
        }

        $update_stmt->close();

        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, created_at) 
                   VALUES (?, 'UPDATE', 'CUSTOMER', ?, 'CUSTOMER', ?, ?, ?, NOW())";
        $log_stmt = $conn->prepare($log_sql);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        
        $old_values = json_encode([
            'first_name' => $customer['first_name'],
            'last_name' => $customer['last_name'],
            'email' => $customer['email'],
            'phone_primary' => $customer['phone_primary']
        ]);
        
        $new_values = json_encode([
            'first_name' => $first_name,
            'last_name' => $last_name,
            'email' => $email,
            'phone_primary' => $phone_primary
        ]);
        
        $log_stmt->bind_param("iisss", $user_id, $customer_id, $old_values, $new_values, $ip_address);
        $log_stmt->execute();
        $log_stmt->close();

        // Commit transaction
        $conn->commit();

        $success_message = "Customer information updated successfully!";
        
        // Redirect to customer view page
        header("Location: view_customer.php?id=" . $customer_id . "&success=updated");
        exit();

    } catch (Exception $e) {
        if ($conn->connect_errno === 0) {
            $conn->rollback();
        }
        $error_message = $e->getMessage();
    }
}

// Get customer segments for dropdown
$segments_sql = "SELECT segment_id, segment_name, description FROM customer_segments ORDER BY segment_name";
$segments = $conn->query($segments_sql);

// Get agents for referral dropdown
$agents_sql = "SELECT user_id, full_name, agent_code FROM users WHERE agent_code IS NOT NULL AND status = 'ACTIVE' ORDER BY full_name";
$agents = $conn->query($agents_sql);

// Get Kenya counties for dropdown
$counties = [
    'Baringo', 'Bomet', 'Bungoma', 'Busia', 'Elgeyo-Marakwet', 'Embu', 'Garissa', 'Homa Bay',
    'Isiolo', 'Kajiado', 'Kakamega', 'Kericho', 'Kiambu', 'Kilifi', 'Kirinyaga', 'Kisii',
    'Kisumu', 'Kitui', 'Kwale', 'Laikipia', 'Lamu', 'Machakos', 'Makueni', 'Mandera',
    'Marsabit', 'Meru', 'Migori', 'Mombasa', 'Murang\'a', 'Nairobi', 'Nakuru', 'Nandi',
    'Narok', 'Nyamira', 'Nyandarua', 'Nyeri', 'Samburu', 'Siaya', 'Taita-Taveta', 'Tana River',
    'Tharaka-Nithi', 'Trans Nzoia', 'Turkana', 'Uasin Gishu', 'Vihiga', 'Wajir', 'West Pokot'
];
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Customer - Ultrasure Insurance')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .customer-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
        }
        
        .customer-avatar {
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            font-size: 1.5rem;
            font-weight: 700;
            color: white;
            margin-right: 15px;
        }
        
        .form-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 4px solid #667eea;
        }
        
        .form-section h5 {
            color: #667eea;
            font-weight: 600;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .form-control, .form-select {
            border-radius: 8px;
            border: 1px solid #e1e5e9;
            padding: 10px 15px;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 8px;
            padding: 10px 25px;
            font-weight: 600;
        }
        
        .btn-secondary {
            border-radius: 8px;
            padding: 10px 25px;
            font-weight: 600;
        }
        
        .alert {
            border-radius: 12px;
            border: none;
            padding: 15px 20px;
        }
        
        .required {
            color: #dc3545;
        }
        
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
    </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 Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Edit Customer</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_customers.php">Customers</a></li>
                                        <li class="breadcrumb-item"><a href="view_customer.php?id=<?php echo $customer_id; ?>"><?php echo htmlspecialchars($customer['customer_number']); ?></a></li>
                                        <li class="breadcrumb-item active">Edit</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Customer Header -->
                    <div class="customer-header">
                        <div class="d-flex align-items-center">
                            <div class="customer-avatar">
                                <?php echo strtoupper(substr($customer['first_name'], 0, 1) . substr($customer['last_name'], 0, 1)); ?>
                            </div>
                            <div>
                                <h5 class="mb-1">Editing: <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?></h5>
                                <p class="mb-0 opacity-75">Customer #<?php echo htmlspecialchars($customer['customer_number']); ?> | Since <?php echo date('M j, Y', strtotime($customer['created_at'])); ?></p>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if($success_message): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="ri-check-line me-2"></i>
                            <?php echo htmlspecialchars($success_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if($error_message): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="ri-error-warning-line me-2"></i>
                            <?php echo htmlspecialchars($error_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Customer Form -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="POST" id="customerForm" novalidate>
                                        
                                        <!-- Personal Information -->
                                        <div class="form-section">
                                            <h5><i class="ri-user-line"></i> Personal Information</h5>
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">First Name <span class="required">*</span></label>
                                                    <input type="text" class="form-control" name="first_name" 
                                                           value="<?php echo htmlspecialchars($_POST['first_name'] ?? $customer['first_name']); ?>" 
                                                           required maxlength="100">
                                                    <div class="invalid-feedback">Please provide a valid first name.</div>
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Middle Name</label>
                                                    <input type="text" class="form-control" name="middle_name" 
                                                           value="<?php echo htmlspecialchars($_POST['middle_name'] ?? $customer['middle_name'] ?? ''); ?>" 
                                                           maxlength="100">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Last Name <span class="required">*</span></label>
                                                    <input type="text" class="form-control" name="last_name" 
                                                           value="<?php echo htmlspecialchars($_POST['last_name'] ?? $customer['last_name']); ?>" 
                                                           required maxlength="100">
                                                    <div class="invalid-feedback">Please provide a valid last name.</div>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Date of Birth</label>
                                                    <input type="date" class="form-control" name="date_of_birth" 
                                                           value="<?php echo $_POST['date_of_birth'] ?? $customer['date_of_birth'] ?? ''; ?>" 
                                                           max="<?php echo date('Y-m-d', strtotime('-18 years')); ?>">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Gender</label>
                                                    <select class="form-select" name="gender">
                                                        <option value="">Select Gender</option>
                                                        <option value="MALE" <?php echo ($_POST['gender'] ?? $customer['gender']) == 'MALE' ? 'selected' : ''; ?>>Male</option>
                                                        <option value="FEMALE" <?php echo ($_POST['gender'] ?? $customer['gender']) == 'FEMALE' ? 'selected' : ''; ?>>Female</option>
                                                        <option value="OTHER" <?php echo ($_POST['gender'] ?? $customer['gender']) == 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Marital Status</label>
                                                    <select class="form-select" name="marital_status">
                                                        <option value="">Select Status</option>
                                                        <option value="SINGLE" <?php echo ($_POST['marital_status'] ?? $customer['marital_status']) == 'SINGLE' ? 'selected' : ''; ?>>Single</option>
                                                        <option value="MARRIED" <?php echo ($_POST['marital_status'] ?? $customer['marital_status']) == 'MARRIED' ? 'selected' : ''; ?>>Married</option>
                                                        <option value="DIVORCED" <?php echo ($_POST['marital_status'] ?? $customer['marital_status']) == 'DIVORCED' ? 'selected' : ''; ?>>Divorced</option>
                                                        <option value="WIDOWED" <?php echo ($_POST['marital_status'] ?? $customer['marital_status']) == 'WIDOWED' ? 'selected' : ''; ?>>Widowed</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Customer Type</label>
                                                    <select class="form-select" name="customer_type">
                                                        <option value="INDIVIDUAL" <?php echo ($_POST['customer_type'] ?? $customer['customer_type']) == 'INDIVIDUAL' ? 'selected' : ''; ?>>Individual</option>
                                                        <option value="CORPORATE" <?php echo ($_POST['customer_type'] ?? $customer['customer_type']) == 'CORPORATE' ? 'selected' : ''; ?>>Corporate</option>
                                                        <option value="GROUP" <?php echo ($_POST['customer_type'] ?? $customer['customer_type']) == 'GROUP' ? 'selected' : ''; ?>>Group</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Contact Information -->
                                        <div class="form-section">
                                            <h5><i class="ri-phone-line"></i> Contact Information</h5>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Primary Phone <span class="required">*</span></label>
                                                    <input type="tel" class="form-control" name="phone_primary" 
                                                           value="<?php echo htmlspecialchars($_POST['phone_primary'] ?? $customer['phone_primary']); ?>" 
                                                           required pattern="(\+254|254|0)[7-9]\d{8}">
                                                    <div class="invalid-feedback">Please provide a valid Kenyan phone number.</div>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Secondary Phone</label>
                                                    <input type="tel" class="form-control" name="phone_secondary" 
                                                           value="<?php echo htmlspecialchars($_POST['phone_secondary'] ?? $customer['phone_secondary'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Email Address</label>
                                                    <input type="email" class="form-control" name="email" 
                                                           value="<?php echo htmlspecialchars($_POST['email'] ?? $customer['email'] ?? ''); ?>">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Preferred Language</label>
                                                    <select class="form-select" name="preferred_language">
                                                        <option value="en" <?php echo ($_POST['preferred_language'] ?? $customer['preferred_language']) == 'en' ? 'selected' : ''; ?>>English</option>
                                                        <option value="sw" <?php echo ($_POST['preferred_language'] ?? $customer['preferred_language']) == 'sw' ? 'selected' : ''; ?>>Swahili</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Communication Preference</label>
                                                    <select class="form-select" name="communication_preference">
                                                        <option value="SMS" <?php echo ($_POST['communication_preference'] ?? $customer['communication_preference']) == 'SMS' ? 'selected' : ''; ?>>SMS</option>
                                                        <option value="EMAIL" <?php echo ($_POST['communication_preference'] ?? $customer['communication_preference']) == 'EMAIL' ? 'selected' : ''; ?>>Email</option>
                                                        <option value="WHATSAPP" <?php echo ($_POST['communication_preference'] ?? $customer['communication_preference']) == 'WHATSAPP' ? 'selected' : ''; ?>>WhatsApp</option>
                                                        <option value="CALL" <?php echo ($_POST['communication_preference'] ?? $customer['communication_preference']) == 'CALL' ? 'selected' : ''; ?>>Phone Call</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Identity & Documents -->
                                        <div class="form-section">
                                            <h5><i class="ri-id-card-line"></i> Identity & Documents</h5>
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">National ID</label>
                                                    <input type="text" class="form-control" name="national_id" 
                                                           value="<?php echo htmlspecialchars($_POST['national_id'] ?? $customer['national_id'] ?? ''); ?>" 
                                                           maxlength="8">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Passport Number</label>
                                                    <input type="text" class="form-control" name="passport_number" 
                                                           value="<?php echo htmlspecialchars($_POST['passport_number'] ?? $customer['passport_number'] ?? ''); ?>" 
                                                           maxlength="20">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Driving License</label>
                                                    <input type="text" class="form-control" name="driving_license" 
                                                           value="<?php echo htmlspecialchars($_POST['driving_license'] ?? $customer['driving_license'] ?? ''); ?>" 
                                                           maxlength="20">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Address Information -->
                                        <div class="form-section">
                                            <h5><i class="ri-map-pin-line"></i> Address Information</h5>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Address Line 1</label>
                                                    <input type="text" class="form-control" name="address_line1" 
                                                           value="<?php echo htmlspecialchars($_POST['address_line1'] ?? $customer['address_line1'] ?? ''); ?>">
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Address Line 2</label>
                                                    <input type="text" class="form-control" name="address_line2" 
                                                           value="<?php echo htmlspecialchars($_POST['address_line2'] ?? $customer['address_line2'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">City/Town</label>
                                                    <input type="text" class="form-control" name="city" 
                                                           value="<?php echo htmlspecialchars($_POST['city'] ?? $customer['city'] ?? ''); ?>">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">County</label>
                                                    <select class="form-select" name="county">
                                                        <option value="">Select County</option>
                                                        <?php foreach($counties as $county): ?>
                                                            <option value="<?php echo $county; ?>" 
                                                                    <?php echo ($_POST['county'] ?? $customer['county']) == $county ? 'selected' : ''; ?>>
                                                                <?php echo $county; ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Postal Code</label>
                                                    <input type="text" class="form-control" name="postal_code" 
                                                           value="<?php echo htmlspecialchars($_POST['postal_code'] ?? $customer['postal_code'] ?? ''); ?>" 
                                                           maxlength="20">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Country</label>
                                                    <select class="form-select" name="country">
                                                        <option value="Kenya" <?php echo ($_POST['country'] ?? $customer['country']) == 'Kenya' ? 'selected' : ''; ?>>Kenya</option>
                                                        <option value="Uganda" <?php echo ($_POST['country'] ?? $customer['country']) == 'Uganda' ? 'selected' : ''; ?>>Uganda</option>
                                                        <option value="Tanzania" <?php echo ($_POST['country'] ?? $customer['country']) == 'Tanzania' ? 'selected' : ''; ?>>Tanzania</option>
                                                        <option value="Rwanda" <?php echo ($_POST['country'] ?? $customer['country']) == 'Rwanda' ? 'selected' : ''; ?>>Rwanda</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Emergency Contact -->
                                       <div class="form-section">
                                           <h5><i class="ri-emergency-stop-line"></i> Emergency Contact</h5>
                                           <div class="row">
                                               <div class="col-md-4 mb-3">
                                                   <label class="form-label">Emergency Contact Name</label>
                                                   <input type="text" class="form-control" name="emergency_contact_name" 
                                                          value="<?php echo htmlspecialchars($_POST['emergency_contact_name'] ?? $customer['emergency_contact_name'] ?? ''); ?>" 
                                                          maxlength="100">
                                               </div>
                                               
                                               <div class="col-md-4 mb-3">
                                                   <label class="form-label">Emergency Contact Phone</label>
                                                   <input type="tel" class="form-control" name="emergency_contact_phone" 
                                                          value="<?php echo htmlspecialchars($_POST['emergency_contact_phone'] ?? $customer['emergency_contact_phone'] ?? ''); ?>">
                                               </div>
                                               
                                               <div class="col-md-4 mb-3">
                                                   <label class="form-label">Relationship</label>
                                                   <input type="text" class="form-control" name="emergency_contact_relationship" 
                                                          value="<?php echo htmlspecialchars($_POST['emergency_contact_relationship'] ?? $customer['emergency_contact_relationship'] ?? ''); ?>" 
                                                          maxlength="50">
                                               </div>
                                           </div>
                                       </div>

                                       <!-- Employment & Financial Information -->
                                       <div class="form-section">
                                           <h5><i class="ri-briefcase-line"></i> Employment & Financial Information</h5>
                                           <div class="row">
                                               <div class="col-md-4 mb-3">
                                                   <label class="form-label">Occupation</label>
                                                   <input type="text" class="form-control" name="occupation" 
                                                          value="<?php echo htmlspecialchars($_POST['occupation'] ?? $customer['occupation'] ?? ''); ?>" 
                                                          maxlength="100">
                                               </div>
                                               
                                               <div class="col-md-4 mb-3">
                                                   <label class="form-label">Employer</label>
                                                   <input type="text" class="form-control" name="employer" 
                                                          value="<?php echo htmlspecialchars($_POST['employer'] ?? $customer['employer'] ?? ''); ?>" 
                                                          maxlength="150">
                                               </div>
                                               
                                               <div class="col-md-4 mb-3">
                                                   <label class="form-label">Monthly Income (KSH)</label>
                                                   <input type="number" class="form-control" name="monthly_income" 
                                                          value="<?php echo $_POST['monthly_income'] ?? $customer['monthly_income'] ?? ''; ?>" 
                                                          min="0" step="0.01">
                                               </div>
                                           </div>
                                       </div>

                                       <!-- Additional Information -->
                                       <div class="form-section">
                                           <h5><i class="ri-information-line"></i> Additional Information</h5>
                                           <div class="row">
                                               <div class="col-md-6 mb-3">
                                                   <label class="form-label">Customer Segment</label>
                                                   <select class="form-select" name="segment_id">
                                                       <option value="">Select Segment</option>
                                                       <?php 
                                                       $segments->data_seek(0);
                                                       while($segment = $segments->fetch_assoc()): ?>
                                                           <option value="<?php echo $segment['segment_id']; ?>" 
                                                                   <?php echo ($_POST['segment_id'] ?? $customer['segment_id']) == $segment['segment_id'] ? 'selected' : ''; ?>>
                                                               <?php echo htmlspecialchars($segment['segment_name']); ?>
                                                               <?php if($segment['description']): ?>
                                                                   - <?php echo htmlspecialchars($segment['description']); ?>
                                                               <?php endif; ?>
                                                           </option>
                                                       <?php endwhile; ?>
                                                   </select>
                                               </div>
                                               
                                               <div class="col-md-6 mb-3">
                                                   <label class="form-label">Referring Agent</label>
                                                   <select class="form-select" name="referring_agent_id">
                                                       <option value="">Select Agent (Optional)</option>
                                                       <?php 
                                                       $agents->data_seek(0);
                                                       while($agent = $agents->fetch_assoc()): ?>
                                                           <option value="<?php echo $agent['user_id']; ?>" 
                                                                   <?php echo ($_POST['referring_agent_id'] ?? $customer['referring_agent_id']) == $agent['user_id'] ? 'selected' : ''; ?>>
                                                               <?php echo htmlspecialchars($agent['full_name'] . ' (' . $agent['agent_code'] . ')'); ?>
                                                           </option>
                                                       <?php endwhile; ?>
                                                   </select>
                                               </div>
                                           </div>
                                           
                                           <div class="row">
                                               <div class="col-md-12 mb-3">
                                                   <label class="form-label">Referral Source</label>
                                                   <input type="text" class="form-control" name="referral_source" 
                                                          value="<?php echo htmlspecialchars($_POST['referral_source'] ?? $customer['referral_source'] ?? ''); ?>" 
                                                          maxlength="100">
                                               </div>
                                           </div>
                                       </div>

                                       <!-- Form Actions -->
                                       <div class="text-end">
                                           <a href="view_customer.php?id=<?php echo $customer_id; ?>" class="btn btn-secondary me-2">
                                               <i class="ri-arrow-left-line me-1"></i> Cancel
                                           </a>
                                           <button type="submit" class="btn btn-primary">
                                               <i class="ri-save-line me-1"></i> Update Customer
                                           </button>
                                       </div>
                                   </form>
                               </div>
                           </div>
                       </div>
                   </div>

               </div>
           </div>
           <?php include 'layouts/footer.php'; ?>
       </div>
   </div>

   <?php include 'layouts/vendor-scripts.php'; ?>
   <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
   
   <script>
       document.addEventListener('DOMContentLoaded', function() {
           const form = document.getElementById('customerForm');
           let formModified = false;
           
           // Track form changes
           const formInputs = document.querySelectorAll('#customerForm input, #customerForm select');
           formInputs.forEach(input => {
               input.addEventListener('change', () => formModified = true);
           });
           
           // Form validation
           form.addEventListener('submit', function(event) {
               if (!form.checkValidity()) {
                   event.preventDefault();
                   event.stopPropagation();
                   
                   // Find first invalid field and focus on it
                   const firstInvalid = form.querySelector(':invalid');
                   if (firstInvalid) {
                       firstInvalid.focus();
                       firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
                   }
               } else {
                   // Show loading state
                   const submitBtn = form.querySelector('button[type="submit"]');
                   const originalText = submitBtn.innerHTML;
                   submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Updating...';
                   submitBtn.disabled = true;
               }
               
               form.classList.add('was-validated');
           });
           
           // Real-time validation feedback
           formInputs.forEach(input => {
               input.addEventListener('blur', function() {
                   if (this.checkValidity()) {
                       this.classList.remove('is-invalid');
                       this.classList.add('is-valid');
                   } else {
                       this.classList.remove('is-valid');
                       this.classList.add('is-invalid');
                   }
               });
               
               input.addEventListener('input', function() {
                   if (this.classList.contains('is-invalid') && this.checkValidity()) {
                       this.classList.remove('is-invalid');
                       this.classList.add('is-valid');
                   }
               });
           });
           
           // Phone number formatting
           const phoneInputs = document.querySelectorAll('input[type="tel"]');
           phoneInputs.forEach(input => {
               input.addEventListener('input', function() {
                   let value = this.value.replace(/\D/g, '');
                   
                   // Auto-format Kenyan numbers
                   if (value.startsWith('254')) {
                       value = '+' + value;
                   } else if (value.startsWith('7') && value.length === 9) {
                       value = '0' + value;
                   }
                   
                   this.value = value;
               });
           });
           
           // National ID validation
           const nationalIdInput = document.querySelector('input[name="national_id"]');
           if (nationalIdInput) {
               nationalIdInput.addEventListener('input', function() {
                   this.value = this.value.replace(/\D/g, '');
                   if (this.value.length > 8) {
                       this.value = this.value.substring(0, 8);
                   }
               });
           }
           
           // Warn about unsaved changes
           window.addEventListener('beforeunload', function(e) {
               if (formModified) {
                   e.preventDefault();
                   e.returnValue = '';
               }
           });
           
           // Auto-hide success alerts
           setTimeout(function() {
               const alerts = document.querySelectorAll('.alert');
               alerts.forEach(alert => {
                   if (alert.classList.contains('alert-success')) {
                       const bsAlert = new bootstrap.Alert(alert);
                       bsAlert.close();
                   }
               });
           }, 5000);
       });
   </script>
</body>
</html>

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