<?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'];
$success_message = '';
$error_message = '';

// Handle form submission for adding/editing segments
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $action = $_POST['action'];
        $segment_name = trim($_POST['segment_name']);
        $description = trim($_POST['description']) ?: null;
        $target_products = !empty($_POST['target_products']) ? json_encode($_POST['target_products']) : null;
        $marketing_approach = trim($_POST['marketing_approach']) ?: null;

        if (empty($segment_name)) {
            throw new Exception('Segment name is required');
        }

        if ($action == 'add') {
            // Check for duplicate segment name
            $check_sql = "SELECT segment_id FROM customer_segments WHERE segment_name = ?";
            $check_stmt = $conn->prepare($check_sql);
            $check_stmt->bind_param("s", $segment_name);
            $check_stmt->execute();
            if ($check_stmt->get_result()->num_rows > 0) {
                throw new Exception('Segment name already exists');
            }
            $check_stmt->close();

            // Insert new segment
            $insert_sql = "INSERT INTO customer_segments (segment_name, description, target_products, marketing_approach, created_at) 
                          VALUES (?, ?, ?, ?, NOW())";
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("ssss", $segment_name, $description, $target_products, $marketing_approach);
            
            if ($stmt->execute()) {
                $success_message = "Customer segment created successfully!";
            } else {
                throw new Exception('Failed to create segment');
            }
            $stmt->close();

        } elseif ($action == 'edit') {
            $segment_id = (int)$_POST['segment_id'];
            
            // Check for duplicate segment name (excluding current segment)
            $check_sql = "SELECT segment_id FROM customer_segments WHERE segment_name = ? AND segment_id != ?";
            $check_stmt = $conn->prepare($check_sql);
            $check_stmt->bind_param("si", $segment_name, $segment_id);
            $check_stmt->execute();
            if ($check_stmt->get_result()->num_rows > 0) {
                throw new Exception('Segment name already exists');
            }
            $check_stmt->close();

            // Update segment
            $update_sql = "UPDATE customer_segments SET 
                          segment_name = ?, description = ?, target_products = ?, marketing_approach = ?
                          WHERE segment_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("ssssi", $segment_name, $description, $target_products, $marketing_approach, $segment_id);
            
            if ($stmt->execute()) {
                $success_message = "Customer segment updated successfully!";
            } else {
                throw new Exception('Failed to update segment');
            }
            $stmt->close();
        }

    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Handle delete request
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $segment_id = (int)$_GET['delete'];
    
    try {
        // Check if segment is in use by customers
        $check_usage_sql = "SELECT COUNT(*) as usage_count FROM customers WHERE segment_id = ?";
        $check_stmt = $conn->prepare($check_usage_sql);
        $check_stmt->bind_param("i", $segment_id);
        $check_stmt->execute();
        $usage_count = $check_stmt->get_result()->fetch_assoc()['usage_count'];
        $check_stmt->close();

        if ($usage_count > 0) {
            throw new Exception("Cannot delete segment. It is currently assigned to $usage_count customer(s).");
        }

        // Delete segment
        $delete_sql = "DELETE FROM customer_segments WHERE segment_id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param("i", $segment_id);
        
        if ($delete_stmt->execute()) {
            $success_message = "Customer segment deleted successfully!";
        } else {
            throw new Exception('Failed to delete segment');
        }
        $delete_stmt->close();

    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Get all customer segments with customer counts
$segments_sql = "SELECT 
    cs.*,
    COUNT(c.customer_id) as customer_count,
    COUNT(CASE WHEN c.is_active = 1 THEN c.customer_id END) as active_customers
FROM customer_segments cs
LEFT JOIN customers c ON cs.segment_id = c.segment_id
GROUP BY cs.segment_id, cs.segment_name, cs.description, cs.target_products, cs.marketing_approach, cs.created_at
ORDER BY cs.segment_name";

$segments = $conn->query($segments_sql);

// Get product categories for targeting
$products_sql = "SELECT category_id, category_name FROM product_categories WHERE is_active = 1 ORDER BY category_name";
$products = $conn->query($products_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Customer Segments - Ultrasure Insurance')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .segment-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            margin-bottom: 20px;
        }
        
        .segment-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }
        
        .segment-card .card-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-bottom: 1px solid #dee2e6;
            border-radius: 15px 15px 0 0;
            padding: 20px;
        }
        
        .segment-icon {
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            font-size: 1.5rem;
            margin-right: 15px;
        }
        
        .stats-badge {
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
            margin-right: 10px;
            margin-bottom: 5px;
            display: inline-block;
        }
        
        .modal-content {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0;
            border-bottom: none;
        }
        
        .form-control, .form-select {
            border-radius: 10px;
            border: 1px solid #e1e5e9;
            padding: 12px 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: 10px;
            padding: 10px 25px;
            font-weight: 600;
        }
        
        .target-products {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 10px;
        }
        
        .target-products .badge {
            font-size: 0.75rem;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }
    </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">Customer Segments</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">Customer Management</li>
                                        <li class="breadcrumb-item active">Customer Segments</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if($success_message): ?>
                        <div class="row">
                            <div class="col-12">
                                <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>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if($error_message): ?>
                        <div class="row">
                            <div class="col-12">
                                <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>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Header Actions -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="mb-1">Manage Customer Segments</h5>
                                    <p class="text-muted mb-0">Organize customers into targeted segments for better marketing and product recommendations.</p>
                                </div>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#segmentModal" onclick="openAddModal()">
                                    <i class="ri-add-line me-2"></i>Add New Segment
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Customer Segments Grid -->
                    <div class="row">
                        <?php if($segments->num_rows > 0): ?>
                            <?php 
                            $segment_colors = [
                                'primary', 'success', 'info', 'warning', 'danger', 'secondary', 'dark'
                            ];
                            $color_index = 0;
                            ?>
                            <?php while($segment = $segments->fetch_assoc()): ?>
                                <?php 
                                $color = $segment_colors[$color_index % count($segment_colors)];
                                $color_index++;
                                ?>
                                <div class="col-xl-4 col-lg-6">
                                    <div class="segment-card card">
                                        <div class="card-header">
                                            <div class="d-flex align-items-center">
                                                <div class="segment-icon bg-soft-<?php echo $color; ?> text-<?php echo $color; ?>">
                                                    <i class="ri-group-line"></i>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <h5 class="mb-1"><?php echo htmlspecialchars($segment['segment_name']); ?></h5>
                                                    <div class="d-flex gap-2">
                                                        <span class="stats-badge bg-<?php echo $color; ?> text-white">
                                                            <?php echo $segment['customer_count']; ?> Customers
                                                        </span>
                                                        <span class="stats-badge bg-success text-white">
                                                            <?php echo $segment['active_customers']; ?> Active
                                                        </span>
                                                    </div>
                                                </div>
                                                <div class="dropdown">
                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                                        <i class="ri-more-2-line"></i>
                                                    </button>
                                                    <ul class="dropdown-menu">
                                                        <li>
                                                            <a class="dropdown-item" href="#" onclick="editSegment(<?php echo htmlspecialchars(json_encode($segment)); ?>)">
                                                                <i class="ri-edit-line me-2"></i>Edit
                                                            </a>
                                                        </li>
                                                        <li>
                                                            <a class="dropdown-item" href="list_customers.php?segment=<?php echo $segment['segment_id']; ?>">
                                                                <i class="ri-user-line me-2"></i>View Customers
                                                            </a>
                                                        </li>
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li>
                                                            <a class="dropdown-item text-danger" href="#" onclick="deleteSegment(<?php echo $segment['segment_id']; ?>, '<?php echo htmlspecialchars($segment['segment_name']); ?>', <?php echo $segment['customer_count']; ?>)">
                                                                <i class="ri-delete-bin-line me-2"></i>Delete
                                                            </a>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="card-body">
                                            <?php if($segment['description']): ?>
                                                <p class="text-muted mb-3"><?php echo htmlspecialchars($segment['description']); ?></p>
                                            <?php endif; ?>
                                            
                                            <?php if($segment['target_products']): ?>
                                                <div class="mb-3">
                                                    <h6 class="mb-2">Target Products:</h6>
                                                    <div class="target-products">
                                                        <?php 
                                                        $target_products = json_decode($segment['target_products'], true);
                                                        if($target_products && is_array($target_products)):
                                                            foreach($target_products as $product):
                                                        ?>
                                                            <span class="badge bg-soft-info text-info"><?php echo htmlspecialchars($product); ?></span>
                                                        <?php 
                                                            endforeach;
                                                        endif;
                                                        ?>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <?php if($segment['marketing_approach']): ?>
                                                <div class="mb-3">
                                                    <h6 class="mb-2">Marketing Approach:</h6>
                                                    <p class="text-muted small mb-0"><?php echo htmlspecialchars($segment['marketing_approach']); ?></p>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <div class="text-muted small">
                                                <i class="ri-time-line me-1"></i>
                                                Created <?php echo date('M j, Y', strtotime($segment['created_at'])); ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="empty-state">
                                    <i class="ri-group-line"></i>
                                    <h4>No Customer Segments</h4>
                                    <p class="mb-4">Start organizing your customers by creating targeted segments for better marketing and service delivery.</p>
                                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#segmentModal" onclick="openAddModal()">
                                        <i class="ri-add-line me-2"></i>Create First Segment
                                    </button>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

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

    <!-- Add/Edit Segment Modal -->
    <div class="modal fade" id="segmentModal" tabindex="-1" aria-labelledby="segmentModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="segmentModalLabel">Add Customer Segment</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="segmentForm" method="POST">
                    <input type="hidden" name="action" id="formAction" value="add">
                    <input type="hidden" name="segment_id" id="segmentId">
                    
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-12 mb-3">
                                <label class="form-label">Segment Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="segment_name" id="segmentName" required maxlength="100" placeholder="e.g., Young Professionals, SME Owners">
                                <div class="invalid-feedback">Please provide a segment name.</div>
                            </div>
                            
                            <div class="col-12 mb-3">
                                <label class="form-label">Description</label>
                                <textarea class="form-control" name="description" id="segmentDescription" rows="3" placeholder="Describe this customer segment..."></textarea>
                            </div>
                            
                            <div class="col-12 mb-3">
                                <label class="form-label">Target Products</label>
                                <select class="form-select" name="target_products[]" id="targetProducts" multiple>
                                    <?php 
                                    $products->data_seek(0);
                                    while($product = $products->fetch_assoc()): ?>
                                        <option value="<?php echo htmlspecialchars($product['category_name']); ?>">
                                            <?php echo htmlspecialchars($product['category_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                                <div class="form-text">Hold Ctrl/Cmd to select multiple products. This helps recommend appropriate insurance products.</div>
                            </div>
                            
                            <div class="col-12 mb-3">
                                <label class="form-label">Marketing Approach</label>
                                <textarea class="form-control" name="marketing_approach" id="marketingApproach" rows="3" placeholder="Describe the marketing strategy for this segment..."></textarea>
                                <div class="form-text">How should this segment be approached for marketing and sales?</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="ri-save-line me-1"></i>Save Segment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        function openAddModal() {
            document.getElementById('segmentModalLabel').textContent = 'Add Customer Segment';
            document.getElementById('formAction').value = 'add';
            document.getElementById('segmentId').value = '';
            document.getElementById('segmentForm').reset();
            document.getElementById('submitBtn').innerHTML = '<i class="ri-save-line me-1"></i>Save Segment';
        }
        
        function editSegment(segment) {
            document.getElementById('segmentModalLabel').textContent = 'Edit Customer Segment';
            document.getElementById('formAction').value = 'edit';
            document.getElementById('segmentId').value = segment.segment_id;
            document.getElementById('segmentName').value = segment.segment_name;
            document.getElementById('segmentDescription').value = segment.description || '';
            document.getElementById('marketingApproach').value = segment.marketing_approach || '';
            document.getElementById('submitBtn').innerHTML = '<i class="ri-save-line me-1"></i>Update Segment';
            
            // Set target products
            const targetProducts = document.getElementById('targetProducts');
            const selectedProducts = segment.target_products ? JSON.parse(segment.target_products) : [];
            
            for (let i = 0; i < targetProducts.options.length; i++) {
                targetProducts.options[i].selected = selectedProducts.includes(targetProducts.options[i].value);
            }
            
            const modal = new bootstrap.Modal(document.getElementById('segmentModal'));
            modal.show();
        }
        
        function deleteSegment(segmentId, segmentName, customerCount) {
            if (customerCount > 0) {
                Swal.fire({
                    title: 'Cannot Delete Segment',
                    text: `This segment is assigned to ${customerCount} customer(s). Please reassign customers to other segments before deleting.`,
                    icon: 'warning',
                    confirmButtonText: 'Understood'
                });
                return;
            }
            
            Swal.fire({
                title: 'Delete Customer Segment',
                text: `Are you sure you want to delete "${segmentName}"? This action cannot be undone.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Delete'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `customer_segments.php?delete=${segmentId}`;
                }
            });
        }
        
        // Form validation
        document.getElementById('segmentForm').addEventListener('submit', function(e) {
            if (!this.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
            } else {
                // Show loading state
                const submitBtn = document.getElementById('submitBtn');
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';
                submitBtn.disabled = true;
            }
            
            this.classList.add('was-validated');
        });
        
        // Auto-hide success alerts
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert-success');
            alerts.forEach(alert => {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);
    </script>
</body>
</html>

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