<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include session handling
try {
    include_once 'services/session.php';
} catch (Exception $e) {
    die("Error including session.php: " . $e->getMessage());
}

// Check if user is logged in
if (!isset($_SESSION['user']) || empty($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Include database connection
try {
    require_once 'layouts/dbconn.php';
} catch (Exception $e) {
    die("Error including database connection: " . $e->getMessage());
}

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection object not found'));
}

// Function to safely execute queries
if (!function_exists('safeQuery')) {
    function safeQuery($conn, $query, $params = []) {
        try {
            $stmt = $conn->prepare($query);
            if (!$stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            if (!empty($params)) {
                $types = str_repeat('s', count($params));
                $stmt->bind_param($types, ...$params);
            }
            
            $stmt->execute();
            $result = $stmt->get_result();
            $data = $result->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            
            return $data;
        } catch (Exception $e) {
            error_log("Query error: " . $e->getMessage());
            return [];
        }
    }
}

// Initialize variables
$message = '';
$message_text = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'request_quote') {
    $result = submitCustomSolutionRequest($_POST, $conn, $user_id);
    $message = $result['success'] ? 'success' : 'danger';
    $message_text = $result['message'];
}

// Get user data
function getUserData($conn, $user_id) {
    try {
        $users = safeQuery($conn, "SELECT * FROM users WHERE user_id = ?", [$user_id]);
        return $users[0] ?? null;
    } catch (Exception $e) {
        error_log("Error fetching user data: " . $e->getMessage());
        return null;
    }
}

// Get custom solution packages from product_pricing
function getCustomSolutionPackages($conn) {
    try {
        $packages = safeQuery($conn, "
            SELECT pp.*, p.name as product_name, p.short_description, p.long_description, pc.name as category_name
            FROM product_pricing pp
            JOIN products p ON pp.product_id = p.product_id
            JOIN product_categories pc ON p.category_id = pc.category_id
            WHERE pc.slug = 'custom-solutions' AND pp.is_active = 1
            ORDER BY pp.price_usd ASC
        ");
        
        $solution_packages = [];
        foreach ($packages as $row) {
            $features = json_decode($row['features'] ?? '[]', true);
            $providers = json_decode($row['supported_providers'] ?? '[]', true);
            
            $solution_packages[] = [
                'id' => $row['tier_name'],
                'name' => $row['tier_name'] . ' Solution',
                'subtitle' => $row['description'] ?? '',
                'description' => $row['short_description'] ?? '',
                'icon' => $row['tier_name'] === 'Starter' ? '🚀' : ($row['tier_name'] === 'Professional' ? '💼' : '🏢'),
                'starting_price' => $row['price_usd'] * 12, // Convert to yearly
                'price_note' => 'Starting from',
                'timeline' => $row['tier_name'] === 'Starter' ? '2-3 weeks' : ($row['tier_name'] === 'Professional' ? '3-5 weeks' : '6-8 weeks'),
                'badge_type' => $row['tier_name'] === 'Professional' ? 'popular' : 'enterprise',
                'badge_text' => $row['tier_name'] === 'Professional' ? 'Most Popular' : 'Premium',
                'features' => is_array($features) ? $features : [
                    'Custom development included',
                    'Mobile money integration',
                    'Technical support',
                    'Documentation provided'
                ]
            ];
        }
        
        // If no packages found in database, return default ones
        if (empty($solution_packages)) {
            return [
                [
                    'id' => 'starter',
                    'name' => 'Starter Solution',
                    'subtitle' => 'Perfect for small businesses',
                    'description' => 'Get a custom WordPress plugin tailored to your specific payment needs.',
                    'icon' => '🚀',
                    'starting_price' => 2500,
                    'price_note' => 'One-time fee',
                    'timeline' => '2-3 weeks',
                    'badge_type' => 'popular',
                    'badge_text' => 'Most Popular',
                    'features' => [
                        'Custom WordPress plugin development',
                        'Single mobile money provider integration',
                        'Basic payment processing',
                        'Simple admin dashboard',
                        'Email notifications',
                        '30 days of support'
                    ]
                ],
                [
                    'id' => 'professional',
                    'name' => 'Professional Solution',
                    'subtitle' => 'For growing businesses',
                    'description' => 'Comprehensive payment system with multiple provider support and advanced features.',
                    'icon' => '💼',
                    'starting_price' => 5000,
                    'price_note' => 'One-time fee',
                    'timeline' => '3-5 weeks',
                    'badge_type' => 'enterprise',
                    'badge_text' => 'Recommended',
                    'features' => [
                        'Multi-provider integration (MTN, Airtel, etc.)',
                        'Advanced payment flows',
                        'Custom reporting dashboard',
                        'Transaction analytics',
                        'API endpoints',
                        'Webhook notifications'
                    ]
                ],
                [
                    'id' => 'enterprise',
                    'name' => 'Enterprise Solution',
                    'subtitle' => 'For large organizations',
                    'description' => 'Full-scale custom development with unlimited features and enterprise-grade security.',
                    'icon' => '🏢',
                    'starting_price' => 15000,
                    'price_note' => 'Starting from',
                    'timeline' => '6-8 weeks',
                    'badge_type' => 'enterprise',
                    'badge_text' => 'Custom',
                    'features' => [
                        'Unlimited mobile money providers',
                        'Custom web application',
                        'Advanced user management',
                        'Real-time monitoring',
                        'Compliance reporting',
                        'White-label solution'
                    ]
                ]
            ];
        }
        
        return $solution_packages;
    } catch (Exception $e) {
        error_log("Error fetching packages: " . $e->getMessage());
        return [];
    }
}

// Submit custom solution request using support_tickets table
function submitCustomSolutionRequest($data, $conn, $user_id) {
    try {
        // Start transaction
        $conn->begin_transaction();
        
        // Validate required fields
        $required_fields = ['full_name', 'email', 'phone', 'project_type', 'project_description'];
        foreach ($required_fields as $field) {
            if (empty($data[$field])) {
                throw new Exception("Required field '{$field}' is missing.");
            }
        }
        
        // Generate unique ticket number
        $ticket_number = 'CS-' . date('Y') . '-' . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        
        // Prepare subject and description
        $subject = 'Custom Solution Request: ' . ucfirst(str_replace('_', ' ', $data['project_type']));
        
        $description = "CUSTOM SOLUTION REQUEST\n\n";
        $description .= "Contact Information:\n";
        $description .= "Name: " . $data['full_name'] . "\n";
        $description .= "Email: " . $data['email'] . "\n";
        $description .= "Phone: " . $data['phone'] . "\n";
        $description .= "Company: " . ($data['company_name'] ?? 'Not provided') . "\n\n";
        
        $description .= "Project Details:\n";
        $description .= "Type: " . ucfirst(str_replace('_', ' ', $data['project_type'])) . "\n";
        $description .= "Budget Range: " . ($data['budget_range'] ?? 'Not specified') . "\n";
        $description .= "Timeline: " . ($data['timeline'] ?? 'Not specified') . "\n";
        $description .= "Package Selected: " . ($data['package_id'] ?? 'None') . "\n\n";
        
        $description .= "Requirements:\n";
        $description .= $data['project_description'] . "\n\n";
        
        if (!empty($data['requirements']) && is_array($data['requirements'])) {
            $description .= "Additional Requirements:\n";
            foreach ($data['requirements'] as $req) {
                $description .= "- " . ucfirst(str_replace('_', ' ', $req)) . "\n";
            }
            $description .= "\n";
        }
        
        $description .= "Referral Source: " . ($data['referral_source'] ?? 'Not specified') . "\n";
        
        // Insert into support_tickets table
        $stmt = $conn->prepare("
            INSERT INTO support_tickets (
                ticket_number, user_id, subject, description, priority, status, category, created_at
            ) VALUES (?, ?, ?, ?, 'MEDIUM', 'OPEN', 'CUSTOM_DEVELOPMENT', NOW())
        ");
        
        $stmt->bind_param("siss", $ticket_number, $user_id, $subject, $description);
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to insert ticket: " . $stmt->error);
        }
        
        $ticket_id = $conn->insert_id;
        $stmt->close();
        
        // Log activity if activity_log table exists
        try {
            $stmt = $conn->prepare("
                INSERT INTO activity_log (user_id, action, module, logged_at, additional_info) 
                VALUES (?, 'SUBMITTED_CUSTOM_SOLUTION_REQUEST', 'CUSTOM_SOLUTIONS', NOW(), ?)
            ");
            $info = json_encode(['ticket_number' => $ticket_number, 'project_type' => $data['project_type']]);
            $stmt->bind_param("is", $user_id, $info);
            $stmt->execute();
            $stmt->close();
        } catch (Exception $e) {
            // Activity log is optional, continue if it fails
            error_log("Activity log failed: " . $e->getMessage());
        }
        
        // Commit transaction
        $conn->commit();
        
        return [
            'success' => true,
            'message' => "Your custom solution request has been submitted successfully! Ticket number: {$ticket_number}. We'll contact you within 24 hours with a detailed proposal.",
            'ticket_number' => $ticket_number,
            'ticket_id' => $ticket_id
        ];
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        error_log("Error submitting custom solution request: " . $e->getMessage());
        
        return [
            'success' => false,
            'message' => 'Failed to submit your request. Please try again or contact support if the problem persists.',
            'error' => $e->getMessage()
        ];
    }
}

// Get data
$user = getUserData($conn, $user_id);
$solution_packages = getCustomSolutionPackages($conn);
$past_projects = [
    [
        'title' => 'E-commerce Payment Gateway',
        'description' => 'Built a comprehensive WooCommerce integration for a major retailer, supporting MTN and Airtel mobile money with real-time transaction tracking.',
        'technologies' => ['WordPress', 'WooCommerce', 'MTN MoMo API', 'Airtel API', 'PHP', 'MySQL']
    ],
    [
        'title' => 'Multi-Tenant SaaS Platform',
        'description' => 'Developed a white-label payment processing platform allowing businesses to offer mobile money services under their own brand.',
        'technologies' => ['Laravel', 'React', 'PostgreSQL', 'Redis', 'Docker', 'AWS']
    ],
    [
        'title' => 'University Fee Payment System',
        'description' => 'Created a custom student portal for fee payments with automatic reconciliation, receipt generation, and parent notifications.',
        'technologies' => ['PHP', 'MySQL', 'Bootstrap', 'MTN MoMo', 'SMS Gateway', 'PDF Generation']
    ],
    [
        'title' => 'Microfinance Loan Management',
        'description' => 'Built a complete loan management system with mobile money repayments, automated reminders, and financial reporting.',
        'technologies' => ['CodeIgniter', 'MySQL', 'Chart.js', 'Mobile Money APIs', 'Cron Jobs']
    ]
];

$client_testimonials = [
    [
        'quote' => 'ConnectPay transformed our payment processing. The custom solution they built handles over 10,000 transactions monthly with zero downtime.',
        'author_name' => 'Sarah Mukamana',
        'author_title' => 'CTO',
        'company' => 'Kigali Tech Solutions'
    ],
    [
        'quote' => 'We needed a complex multi-tenant platform, and ConnectPay delivered beyond expectations. The system is robust and perfectly matches our business requirements.',
        'author_name' => 'James Kiprotich',
        'author_title' => 'Operations Director',
        'company' => 'PayEase Uganda'
    ],
    [
        'quote' => 'The university fee payment system has revolutionized our financial operations. Students and parents love the convenience.',
        'author_name' => 'Dr. Amina Hassan',
        'author_title' => 'Finance Director',
        'company' => 'Kampala International University'
    ],
    [
        'quote' => 'Professional, reliable, and innovative. ConnectPay helped us launch our fintech product ahead of schedule.',
        'author_name' => 'Michael Ochieng',
        'author_title' => 'Founder & CEO',
        'company' => 'FinTech Innovations Kenya'
    ]
];
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php 
    $title = "Custom Solutions";
    if (file_exists('partials/title-meta.php')) {
        try {
            include_once 'partials/title-meta.php';
        } catch (Exception $e) {
            echo "<title>Custom Solutions - ConnectPay</title>\n";
        }
    } else {
        echo "<title>Custom Solutions - ConnectPay</title>\n";
    }
    ?>
    
    <?php 
    if (file_exists('partials/head-css.php')) {
        try {
            include_once 'partials/head-css.php';
        } catch (Exception $e) {
            echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
            echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
        }
    } else {
        echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">' . "\n";
        echo '<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">' . "\n";
    }
    ?>
    
    <style>
        .solution-card {
            border: 1px solid #e9ecef;
            border-radius: 15px;
            transition: all 0.3s ease;
            height: 100%;
            background: white;
            overflow: hidden;
        }
        
        .solution-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border-color: #007bff;
        }
        
        .solution-featured {
            border: 2px solid #ffc107;
            position: relative;
        }
        
        .featured-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: linear-gradient(45deg, #ffc107, #ff8c00);
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            z-index: 10;
        }
        
        .solution-image {
            height: 150px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
        }
        
        .solution-content {
            padding: 1.5rem;
        }
        
        .solution-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            height: 3rem;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        
        .solution-description {
            color: #6c757d;
            font-size: 0.9rem;
            height: 3rem;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            margin-bottom: 1rem;
        }
        
        .features-list {
            list-style: none;
            padding: 0;
            margin-bottom: 1rem;
        }
        
        .features-list li {
            font-size: 0.85rem;
            color: #495057;
            margin-bottom: 0.5rem;
            padding-left: 1.5rem;
            position: relative;
        }
        
        .features-list li:before {
            content: "✓";
            color: #28a745;
            font-weight: bold;
            position: absolute;
            left: 0;
        }
        
        .solution-price {
            font-size: 1.5rem;
            font-weight: 700;
            color: #28a745;
            margin-bottom: 0.5rem;
        }
        
        .solution-footer {
            padding: 1rem 1.5rem;
            background: #f8f9fa;
            border-top: 1px solid #e9ecef;
        }
        
        .hero-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 3rem 2rem;
            margin-bottom: 2rem;
            text-align: center;
        }
        
        .hero-stats {
            display: flex;
            justify-content: center;
            gap: 2rem;
            flex-wrap: wrap;
            margin: 2rem 0;
        }
        
        .hero-stat {
            text-align: center;
        }
        
        .hero-stat-number {
            font-size: 2rem;
            font-weight: 700;
            display: block;
            line-height: 1;
        }
        
        .hero-stat-label {
            font-size: 0.875rem;
            opacity: 0.9;
            margin-top: 0.25rem;
        }
        
        .project-card, .testimonial-card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .project-card:hover, .testimonial-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .tech-tag {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            padding: 0.25rem 0.5rem;
            border-radius: 15px;
            font-size: 0.75rem;
            margin-right: 0.5rem;
            margin-bottom: 0.25rem;
            display: inline-block;
        }
        
        .process-steps {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin: 2rem 0;
        }
        
        .process-step {
            text-align: center;
            padding: 1.5rem;
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 15px;
        }
        
        .step-number {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background: #007bff;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            font-weight: 600;
            margin: 0 auto 1rem auto;
        }
        
        .form-section {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 15px;
            padding: 2rem;
            margin-top: 2rem;
        }
        
        .testimonial-author {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-top: 1rem;
        }
        
        .author-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: #6c757d;
        }
    </style>
</head>

<body>

<div id="wrapper">
    <?php 
    $pagetitle = "Custom Solutions"; 
    if (file_exists('partials/menu.php')) {
        try {
            include_once 'partials/menu.php';
        } catch (Exception $e) {
            echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                    <div class="container">
                        <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                        <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                    </div>
                  </nav>';
        }
    } else {
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="customer-dashboard.php">ConnectPay</a>
                    <span class="navbar-text">Welcome, ' . htmlspecialchars($user_name) . '</span>
                </div>
              </nav>';
    }
    ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">

                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="<?php echo ($user_role === 'Customer') ? 'customer-dashboard.php' : 'index.php'; ?>">Dashboard</a></li>
                                    <li class="breadcrumb-item">Plugin Store</li>
                                    <li class="breadcrumb-item active">Custom Solutions</li>
                                </ol>
                            </div>
                            <h4 class="page-title">Custom Solutions</h4>
                        </div>
                    </div>
                </div>

                <!-- Hero Section -->
                <div class="row">
                    <div class="col-12">
                        <div class="hero-section">
                            <h2 class="mb-3">
                                <i class="fas fa-cogs me-2"></i>
                                Enterprise Payment Solutions
                            </h2>
                            <p class="mb-4 opacity-90">
                                Need something beyond our standard plugins? Our expert team creates custom mobile money integrations, 
                                enterprise payment systems, and bespoke WordPress solutions tailored to your business needs.
                            </p>
                            
                            <div class="hero-stats">
                                <div class="hero-stat">
                                    <span class="hero-stat-number">50+</span>
                                    <div class="hero-stat-label">Custom Projects</div>
                                </div>
                                <div class="hero-stat">
                                    <span class="hero-stat-number">98%</span>
                                    <div class="hero-stat-label">Client Satisfaction</div>
                                </div>
                                <div class="hero-stat">
                                    <span class="hero-stat-number">2-8</span>
                                    <div class="hero-stat-label">Weeks Delivery</div>
                                </div>
                                <div class="hero-stat">
                                    <span class="hero-stat-number">24/7</span>
                                    <div class="hero-stat-label">Support Included</div>
                                </div>
                            </div>
                            
                            <div>
                                <a href="#request-quote" class="btn btn-light btn-lg me-2">
                                    <i class="fas fa-paper-plane me-1"></i>
                                    Get Custom Quote
                                </a>
                                <a href="#past-projects" class="btn btn-outline-light btn-lg">
                                    <i class="fas fa-eye me-1"></i>
                                    View Our Work
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Show message if form was submitted -->
                <?php if (!empty($message)): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="alert alert-<?php echo htmlspecialchars($message); ?> alert-dismissible fade show">
                            <i class="fas fa-<?php echo $message === 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-2"></i>
                            <?php echo htmlspecialchars($message_text); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Solution Packages -->
                <div class="row">
                    <div class="col-12">
                        <div class="mb-4">
                            <h4>
                                <i class="fas fa-box-open me-2"></i>
                                Custom Solution Packages
                            </h4>
                            <p class="text-muted">Choose from our pre-designed packages or request a fully custom solution</p>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <?php if (!empty($solution_packages) && is_array($solution_packages)): ?>
                        <?php foreach ($solution_packages as $package): ?>
                        <div class="col-xl-4 col-md-6 mb-4">
                            <div class="solution-card <?php echo $package['badge_type'] === 'popular' ? 'solution-featured' : ''; ?>">
                                <?php if ($package['badge_type'] === 'popular'): ?>
                                <div class="featured-badge">
                                    <i class="fas fa-star me-1"></i>
                                    <?php echo htmlspecialchars($package['badge_text'] ?? 'Featured'); ?>
                                </div>
                                <?php endif; ?>
                                
                                <!-- Package Image/Icon -->
                                <div class="solution-image">
                                    <?php echo $package['icon'] ?? '📦'; ?>
                                </div>
                                
                                <div class="solution-content">
                                    <!-- Package Title -->
                                    <h5 class="solution-title">
                                        <?php echo htmlspecialchars($package['name'] ?? 'Package'); ?>
                                    </h5>
                                    
                                    <!-- Package Subtitle -->
                                    <p class="text-muted small mb-2">
                                        <?php echo htmlspecialchars($package['subtitle'] ?? ''); ?>
                                    </p>
                                    
                                    <!-- Description -->
                                    <p class="solution-description">
                                        <?php echo htmlspecialchars($package['description'] ?? ''); ?>
                                    </p>
                                    
                                    <!-- Features -->
                                    <?php if (!empty($package['features']) && is_array($package['features'])): ?>
                                    <ul class="features-list">
                                        <?php foreach (array_slice($package['features'], 0, 5) as $feature): ?>
                                        <li><?php echo htmlspecialchars($feature); ?></li>
                                        <?php endforeach; ?>
                                        <?php if (count($package['features']) > 5): ?>
                                        <li class="text-muted">+<?php echo count($package['features']) - 5; ?> more features</li>
                                        <?php endif; ?>
                                    </ul>
                                    <?php endif; ?>
                                    
                                    <!-- Timeline -->
                                    <div class="mb-3">
                                        <small class="text-muted text-uppercase fw-bold">Delivery Timeline</small>
                                        <div class="fw-medium">
                                            <?php echo htmlspecialchars($package['timeline'] ?? 'Contact us'); ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Price -->
                                    <div class="solution-price">
                                        $<?php echo number_format($package['starting_price'] ?? 0); ?>
                                        <small class="text-muted d-block fs-6 fw-normal">
                                            <?php echo htmlspecialchars($package['price_note'] ?? ''); ?>
                                        </small>
                                    </div>
                                </div>
                                
                                <div class="solution-footer">
                                    <div class="d-grid gap-2">
                                        <button class="btn btn-outline-primary" onclick="selectPackage('<?php echo htmlspecialchars($package['id'] ?? ''); ?>')">
                                            <i class="fas fa-paper-plane me-1"></i>
                                            Request Quote
                                        </button>
                                        <a href="tel:+211123456789" class="btn btn-primary">
                                            <i class="fas fa-phone me-1"></i>
                                            Discuss Details
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="col-12">
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                Custom solution packages are currently being updated. Please contact us directly for pricing and availability.
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Development Process -->
                <div class="row">
                    <div class="col-12">
                        <div class="text-center mb-4">
                            <h4>
                                <i class="fas fa-cogs me-2"></i>
                                Our Development Process
                            </h4>
                            <p class="text-muted">From concept to deployment, we follow a proven process</p>
                        </div>
                        
                        <div class="process-steps">
                            <div class="process-step">
                                <div class="step-number">1</div>
                                <h5>Discovery & Planning</h5>
                                <p class="text-muted">We analyze your requirements, understand your business goals, and create a detailed project plan.</p>
                            </div>
                            <div class="process-step">
                                <div class="step-number">2</div>
                                <h5>Design & Architecture</h5>
                                <p class="text-muted">Our team designs the system architecture and creates wireframes for user interface components.</p>
                            </div>
                            <div class="process-step">
                                <div class="step-number">3</div>
                                <h5>Development & Testing</h5>
                                <p class="text-muted">We build your solution using best practices, with continuous testing throughout the development cycle.</p>
                            </div>
                            <div class="process-step">
                                <div class="step-number">4</div>
                                <h5>Deployment & Support</h5>
                                <p class="text-muted">We handle deployment and provide ongoing support to ensure your solution runs smoothly.</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Past Projects Showcase -->
                <div class="row" id="past-projects">
                    <div class="col-12">
                        <div class="text-center mb-4">
                            <h4>
                                <i class="fas fa-trophy me-2"></i>
                                Featured Projects
                            </h4>
                            <p class="text-muted">See what we've built for other clients</p>
                        </div>
                        
                        <div class="row">
                            <?php if (!empty($past_projects) && is_array($past_projects)): ?>
                                <?php foreach ($past_projects as $project): ?>
                                <div class="col-lg-6 mb-4">
                                    <div class="project-card">
                                        <h5 class="mb-3">
                                            <i class="fas fa-project-diagram me-2 text-primary"></i>
                                            <?php echo htmlspecialchars($project['title'] ?? 'Project'); ?>
                                        </h5>
                                        <p class="text-muted mb-3"><?php echo htmlspecialchars($project['description'] ?? ''); ?></p>
                                        <?php if (!empty($project['technologies']) && is_array($project['technologies'])): ?>
                                        <div>
                                            <small class="text-muted text-uppercase fw-bold">Technologies Used:</small>
                                            <div class="mt-2">
                                                <?php foreach ($project['technologies'] as $tech): ?>
                                                <span class="tech-tag"><?php echo htmlspecialchars($tech); ?></span>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="col-12">
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle me-2"></i>
                                        Project showcase is currently being updated. Contact us to learn about our recent work.
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Client Testimonials -->
                <div class="row">
                    <div class="col-12">
                        <div class="text-center mb-4">
                            <h4>
                                <i class="fas fa-quote-left me-2"></i>
                                What Our Clients Say
                            </h4>
                            <p class="text-muted">Testimonials from businesses we've helped</p>
                        </div>
                        
                        <div class="row">
                            <?php if (!empty($client_testimonials) && is_array($client_testimonials)): ?>
                                <?php foreach ($client_testimonials as $testimonial): ?>
                                <div class="col-lg-6 mb-4">
                                    <div class="testimonial-card">
                                        <blockquote class="mb-3">
                                            <i class="fas fa-quote-left text-muted me-2"></i>
                                            <em><?php echo htmlspecialchars($testimonial['quote'] ?? ''); ?></em>
                                        </blockquote>
                                        <div class="testimonial-author">
                                            <div class="author-avatar">
                                                <?php echo strtoupper(substr($testimonial['author_name'] ?? 'AA', 0, 2)); ?>
                                            </div>
                                            <div>
                                                <div class="fw-bold"><?php echo htmlspecialchars($testimonial['author_name'] ?? 'Anonymous'); ?></div>
                                                <small class="text-muted">
                                                    <?php echo htmlspecialchars($testimonial['author_title'] ?? ''); ?>
                                                    <?php if (!empty($testimonial['company'])): ?>
                                                        , <?php echo htmlspecialchars($testimonial['company']); ?>
                                                    <?php endif; ?>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="col-12">
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle me-2"></i>
                                        Client testimonials are currently being updated. Contact us for references from our satisfied clients.
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Request Quote Form -->
                <div class="row" id="request-quote">
                    <div class="col-12">
                        <div class="form-section">
                            <div class="text-center mb-4">
                                <h4>
                                    <i class="fas fa-paper-plane me-2"></i>
                                    Request Custom Solution Quote
                                </h4>
                                <p class="text-muted">
                                    Tell us about your project and we'll provide a detailed quote within 24 hours
                                </p>
                            </div>
                            
                            <form method="POST" action="" id="quoteForm">
                                <input type="hidden" name="action" value="request_quote">
                                <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user_id); ?>">
                                <input type="hidden" id="selected_package" name="package_id" value="">
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Full Name *</label>
                                            <input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($user['full_name'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Email Address *</label>
                                            <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Company Name</label>
                                            <input type="text" name="company_name" class="form-control" value="<?php echo htmlspecialchars($user['company_name'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Phone Number *</label>
                                            <input type="tel" name="phone" class="form-control" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Project Type *</label>
                                            <select name="project_type" class="form-select" required>
                                                <option value="">Select project type</option>
                                                <option value="payment_gateway">Custom Payment Gateway</option>
                                                <option value="ecommerce_integration">E-commerce Integration</option>
                                                <option value="api_development">API Development</option>
                                                <option value="wordpress_plugin">WordPress Plugin</option>
                                                <option value="web_application">Web Application</option>
                                                <option value="mobile_app">Mobile Application</option>
                                                <option value="other">Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Budget Range</label>
                                            <select name="budget_range" class="form-select">
                                                <option value="">Select budget range</option>
                                                <option value="under_5k">Under $5,000</option>
                                                <option value="5k_15k">$5,000 - $15,000</option>
                                                <option value="15k_30k">$15,000 - $30,000</option>
                                                <option value="30k_50k">$30,000 - $50,000</option>
                                                <option value="over_50k">Over $50,000</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Project Description *</label>
                                    <textarea name="project_description" class="form-control" rows="4" placeholder="Please describe your project requirements, goals, and any specific features you need..." required></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Additional Requirements</label>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-check">
                                                <input type="checkbox" name="requirements[]" value="api_integration" class="form-check-input" id="api_integration">
                                                <label class="form-check-label" for="api_integration">API Integration</label>
                                            </div>
                                            <div class="form-check">
                                                <input type="checkbox" name="requirements[]" value="mobile_responsive" class="form-check-input" id="mobile_responsive">
                                                <label class="form-check-label" for="mobile_responsive">Mobile Responsive</label>
                                            </div>
                                            <div class="form-check">
                                                <input type="checkbox" name="requirements[]" value="admin_dashboard" class="form-check-input" id="admin_dashboard">
                                                <label class="form-check-label" for="admin_dashboard">Admin Dashboard</label>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-check">
                                                <input type="checkbox" name="requirements[]" value="user_management" class="form-check-input" id="user_management">
                                                <label class="form-check-label" for="user_management">User Management</label>
                                            </div>
                                            <div class="form-check">
                                                <input type="checkbox" name="requirements[]" value="reporting_analytics" class="form-check-input" id="reporting_analytics">
                                                <label class="form-check-label" for="reporting_analytics">Reporting & Analytics</label>
                                            </div>
                                            <div class="form-check">
                                                <input type="checkbox" name="requirements[]" value="third_party_integration" class="form-check-input" id="third_party_integration">
                                                <label class="form-check-label" for="third_party_integration">Third-party Integration</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Preferred Timeline</label>
                                            <select name="timeline" class="form-select">
                                                <option value="">Select timeline</option>
                                                <option value="urgent">ASAP (Rush delivery)</option>
                                                <option value="1_month">1 Month</option>
                                                <option value="2_months">2 Months</option>
                                                <option value="3_months">3 Months</option>
                                                <option value="flexible">Flexible</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">How did you hear about us?</label>
                                            <select name="referral_source" class="form-select">
                                                <option value="">Select source</option>
                                                <option value="google_search">Google Search</option>
                                                <option value="social_media">Social Media</option>
                                                <option value="referral">Referral</option>
                                                <option value="existing_customer">Existing Customer</option>
                                                <option value="other">Other</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="text-center pt-3 border-top">
                                    <button type="submit" class="btn btn-primary btn-lg px-5" id="submitBtn">
                                        <i class="fas fa-paper-plane me-2"></i>
                                        Submit Quote Request
                                    </button>
                                    <p class="small text-muted mt-3 mb-0">
                                        By submitting this form, you agree to our terms of service and privacy policy. 
                                        We'll contact you within 24 hours with a detailed quote.
                                    </p>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?php 
        if (file_exists('partials/footer.php')) {
            try {
                include_once 'partials/footer.php';
            } catch (Exception $e) {
                echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
            }
        } else {
            echo '<footer class="bg-light text-center py-3 mt-5"><p>&copy; 2024 ConnectPay Platform</p></footer>';
        }
        ?>
    </div>
</div>

<?php 
if (file_exists('partials/footer-scripts.php')) {
    try {
        include_once 'partials/footer-scripts.php';
    } catch (Exception $e) {
        echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
    }
} else {
    echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>' . "\n";
}
?>

<script>
console.log('Custom Solutions page loaded');

// Function to select a package and scroll to form
function selectPackage(packageId) {
    const selectedPackageInput = document.getElementById('selected_package');
    if (selectedPackageInput) {
        selectedPackageInput.value = packageId;
    }
    
    const requestQuoteSection = document.getElementById('request-quote');
    if (requestQuoteSection) {
        requestQuoteSection.scrollIntoView({ behavior: 'smooth' });
    }
    
    // Update project type based on package
    const projectTypeSelect = document.querySelector('select[name="project_type"]');
    if (projectTypeSelect) {
        if (packageId === 'starter') {
            projectTypeSelect.value = 'wordpress_plugin';
        } else if (packageId === 'professional') {
            projectTypeSelect.value = 'payment_gateway';
        } else if (packageId === 'enterprise') {
            projectTypeSelect.value = 'web_application';
        }
    }
    
    // Show success message
    showToast('Package selected! Please fill out the form below.', 'success');
}

// Form validation
const form = document.getElementById('quoteForm');
if (form) {
    form.addEventListener('submit', function(e) {
        const requiredFields = this.querySelectorAll('[required]');
        let isValid = true;
        
        requiredFields.forEach(field => {
            field.classList.remove('is-invalid');
            if (!field.value.trim()) {
                isValid = false;
                field.classList.add('is-invalid');
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            showToast('Please fill in all required fields.', 'error');
            
            // Scroll to first invalid field
            const firstInvalid = this.querySelector('.is-invalid');
            if (firstInvalid) {
                firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstInvalid.focus();
            }
        } else {
            // Show loading state
            const submitButton = document.getElementById('submitBtn');
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Submitting...';
            }
        }
    });
    
    // Real-time validation feedback
    const requiredFields = form.querySelectorAll('[required]');
    requiredFields.forEach(field => {
        field.addEventListener('blur', function() {
            this.classList.remove('is-invalid', 'is-valid');
            if (!this.value.trim()) {
                this.classList.add('is-invalid');
            } else {
                this.classList.add('is-valid');
            }
        });
    });
}

// Smooth scroll for anchor links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const targetId = this.getAttribute('href');
        const target = document.querySelector(targetId);
        if (target) {
            target.scrollIntoView({ 
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
});

// Show toast notifications
function showToast(message, type) {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'success' ? 'success' : 'danger'} position-fixed`;
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check' : 'exclamation'}-circle me-2"></i>
        ${message}
        <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
    `;
    
    document.body.appendChild(toast);
    
    // Auto remove after 4 seconds
    setTimeout(() => {
        if (toast.parentElement) {
            toast.remove();
        }
    }, 4000);
}

// Animate stats on scroll
const observerOptions = {
    threshold: 0.5,
    rootMargin: '0px 0px -100px 0px'
};

const statsObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const statNumbers = entry.target.querySelectorAll('.hero-stat-number');
            statNumbers.forEach(stat => {
                const finalValue = stat.textContent.replace(/[^\d]/g, '');
                const suffix = stat.textContent.replace(/[\d]/g, '');
                let currentValue = 0;
                
                const increment = () => {
                    const target = parseInt(finalValue);
                    const step = Math.ceil(target / 30);
                    
                    if (currentValue < target) {
                        currentValue = Math.min(currentValue + step, target);
                        stat.textContent = currentValue + suffix;
                        setTimeout(increment, 50);
                    } else {
                        stat.textContent = finalValue + suffix;
                    }
                };
                
                stat.textContent = '0' + suffix;
                setTimeout(increment, 200);
            });
            statsObserver.unobserve(entry.target);
        }
    });
}, observerOptions);

const heroStats = document.querySelector('.hero-stats');
if (heroStats) {
    statsObserver.observe(heroStats);
}

console.log('✅ Custom Solutions page fully initialized');
</script>

</body>
</html>