<?php
/**
 * Functions for Custom Solutions Module
 * ConnectPay MoMo Plugin Distribution Platform
 * 
 * This file contains all the functions needed for the custom solutions page
 * following the shadcn/ui design principles with clean, modern styling
 */

// Ensure database connection
require_once 'layouts/dbconn.php';

/**
 * Get user by ID
 * @param int $user_id
 * @return array|null User data or null if not found
 */
function getUserById($user_id) {
    global $conn;
    
    if (!$user_id || $user_id <= 0) {
        return null;
    }
    
    try {
        $stmt = $conn->prepare("
            SELECT u.*, ur.role_name, ur.role_id 
            FROM users u 
            LEFT JOIN user_roles ur ON u.role_id = ur.role_id 
            WHERE u.user_id = ?
        ");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();
        
        return $user;
    } catch (Exception $e) {
        error_log("Error fetching user by ID: " . $e->getMessage());
        return null;
    }
}

/**
 * Get custom solution packages
 * @return array Array of solution packages
 */
function getCustomSolutionPackages() {
    return [
        [
            'id' => 'starter',
            'name' => 'Starter Solution',
            'subtitle' => 'Perfect for small businesses',
            'description' => 'Get a custom WordPress plugin tailored to your specific payment needs. Includes basic mobile money integration with one provider and essential features.',
            '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',
                'Source code included',
                'Installation assistance'
            ]
        ],
        [
            'id' => 'professional',
            'name' => 'Professional Solution',
            'subtitle' => 'For growing businesses',
            'description' => 'Comprehensive payment system with multiple provider support, advanced features, and enhanced security for businesses processing higher volumes.',
            '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',
                '90 days of support',
                'Training session included'
            ]
        ],
        [
            'id' => 'enterprise',
            'name' => 'Enterprise Solution',
            'subtitle' => 'For large organizations',
            'description' => 'Full-scale custom development with unlimited features, dedicated support, and enterprise-grade security for large organizations.',
            'icon' => '🏢',
            'starting_price' => 15000,
            'price_note' => 'Starting from',
            'timeline' => '6-8 weeks',
            'badge_type' => 'custom',
            'badge_text' => 'Custom',
            'features' => [
                'Unlimited mobile money providers',
                'Custom web application',
                'Advanced user management',
                'Real-time monitoring',
                'Compliance reporting',
                'White-label solution',
                '1 year of premium support',
                'Dedicated project manager'
            ]
        ]
    ];
}

/**
 * Get past projects for showcase
 * @return array Array of past projects
 */
function getPastProjects() {
    return [
        [
            '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']
        ]
    ];
}

/**
 * Get client testimonials
 * @return array Array of client testimonials
 */
function getClientTestimonials() {
    return [
        [
            'quote' => 'ConnectPay transformed our payment processing. The custom solution they built handles over 10,000 transactions monthly with zero downtime. Their support team is exceptional.',
            '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, scalable, 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, and our admin team saves hours daily.',
            'author_name' => 'Dr. Amina Hassan',
            'author_title' => 'Finance Director',
            'company' => 'Kampala International University'
        ],
        [
            'quote' => 'Professional, reliable, and innovative. ConnectPay\'s custom solution helped us launch our fintech product ahead of schedule. Highly recommended for serious businesses.',
            'author_name' => 'Michael Ochieng',
            'author_title' => 'Founder & CEO',
            'company' => 'FinTech Innovations Kenya'
        ]
    ];
}

/**
 * Submit custom solution request
 * @param array $data Form data
 * @return array Result with success status and message
 */
function submitCustomSolutionRequest($data) {
    global $conn;
    
    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.");
            }
        }
        
        // Sanitize and prepare data
        $user_id = (int)$data['user_id'];
        $full_name = trim($data['full_name']);
        $email = trim($data['email']);
        $company_name = trim($data['company_name'] ?? '');
        $phone = trim($data['phone']);
        $project_type = trim($data['project_type']);
        $budget_range = trim($data['budget_range'] ?? '');
        $project_description = trim($data['project_description']);
        $timeline = trim($data['timeline'] ?? '');
        $referral_source = trim($data['referral_source'] ?? '');
        $package_id = trim($data['package_id'] ?? '');
        
        // Process requirements array
        $requirements = [];
        if (isset($data['requirements']) && is_array($data['requirements'])) {
            $requirements = $data['requirements'];
        }
        $requirements_json = json_encode($requirements);
        
        // Generate unique quote request number
        $quote_number = 'CSQ-' . date('Y') . '-' . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        
        // Insert into custom_solution_requests table
        $stmt = $conn->prepare("
            INSERT INTO custom_solution_requests (
                quote_number, user_id, full_name, email, company_name, phone,
                project_type, budget_range, project_description, additional_requirements,
                timeline, referral_source, package_id, status, priority,
                created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', 'MEDIUM', NOW(), NOW())
        ");
        
        $stmt->bind_param("sisssssssssss", 
            $quote_number, $user_id, $full_name, $email, $company_name, $phone,
            $project_type, $budget_range, $project_description, $requirements_json,
            $timeline, $referral_source, $package_id
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to insert quote request: " . $stmt->error);
        }
        
        $request_id = $conn->insert_id;
        $stmt->close();
        
        // Log the activity
        logActivity($user_id, 'custom_solution_request', 'submitted', [
            'request_id' => $request_id,
            'quote_number' => $quote_number,
            'project_type' => $project_type
        ]);
        
        // Send notification email to admin team
        sendCustomSolutionNotification($request_id, $data);
        
        // Send confirmation email to user
        sendCustomSolutionConfirmation($email, $full_name, $quote_number);
        
        // Commit transaction
        $conn->commit();
        
        return [
            'success' => true,
            'message' => "Your custom solution request has been submitted successfully! Quote number: {$quote_number}. We'll contact you within 24 hours with a detailed proposal.",
            'quote_number' => $quote_number,
            'request_id' => $request_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()
        ];
    }
}

/**
 * Log user activity
 * @param int $user_id
 * @param string $action
 * @param string $status
 * @param array $metadata
 */
function logActivity($user_id, $action, $status, $metadata = []) {
    global $conn;
    
    try {
        $stmt = $conn->prepare("
            INSERT INTO activity_logs (
                user_id, action, status, metadata, ip_address, user_agent, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $metadata_json = json_encode($metadata);
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        $stmt->bind_param("isssss", $user_id, $action, $status, $metadata_json, $ip_address, $user_agent);
        $stmt->execute();
        $stmt->close();
        
    } catch (Exception $e) {
        error_log("Error logging activity: " . $e->getMessage());
    }
}

/**
 * Send notification email to admin team
 * @param int $request_id
 * @param array $data
 */
function sendCustomSolutionNotification($request_id, $data) {
    // Get admin emails from database or config
    $admin_emails = ['admin@connectpay.co.ss', 'sales@connectpay.co.ss'];
    
    $subject = "New Custom Solution Request - {$data['project_type']}";
    
    $message = "
    <h2>New Custom Solution Request</h2>
    <p><strong>Request ID:</strong> {$request_id}</p>
    <p><strong>Client:</strong> {$data['full_name']} ({$data['email']})</p>
    <p><strong>Company:</strong> " . ($data['company_name'] ?: 'Not provided') . "</p>
    <p><strong>Phone:</strong> {$data['phone']}</p>
    <p><strong>Project Type:</strong> {$data['project_type']}</p>
    <p><strong>Budget Range:</strong> " . ($data['budget_range'] ?: 'Not specified') . "</p>
    <p><strong>Timeline:</strong> " . ($data['timeline'] ?: 'Not specified') . "</p>
    
    <h3>Project Description:</h3>
    <p>" . nl2br(htmlspecialchars($data['project_description'])) . "</p>
    
    <p><strong>Referral Source:</strong> " . ($data['referral_source'] ?: 'Not specified') . "</p>
    
    <p>Please review and respond within 24 hours.</p>
    ";
    
    $headers = [
        'Content-Type' => 'text/html; charset=UTF-8',
        'From' => 'noreply@connectpay.co.ss',
        'Reply-To' => $data['email']
    ];
    
    foreach ($admin_emails as $email) {
        wp_mail($email, $subject, $message, $headers);
    }
}

/**
 * Send confirmation email to user
 * @param string $email
 * @param string $name
 * @param string $quote_number
 */
function sendCustomSolutionConfirmation($email, $name, $quote_number) {
    $subject = "Custom Solution Request Received - {$quote_number}";
    
    $message = "
    <h2>Thank you for your custom solution request!</h2>
    
    <p>Dear {$name},</p>
    
    <p>We have received your custom solution request with quote number: <strong>{$quote_number}</strong></p>
    
    <p>Our team will review your requirements and contact you within 24 hours with:</p>
    <ul>
        <li>Detailed project proposal</li>
        <li>Accurate pricing estimate</li>
        <li>Project timeline</li>
        <li>Next steps</li>
    </ul>
    
    <p>In the meantime, feel free to contact us at:</p>
    <ul>
        <li>📧 Email: sales@connectpay.co.ss</li>
        <li>📱 Phone: +211 123 456 789</li>
        <li>💬 WhatsApp: +211 123 456 789</li>
    </ul>
    
    <p>Best regards,<br>
    ConnectPay Custom Solutions Team</p>
    ";
    
    $headers = [
        'Content-Type' => 'text/html; charset=UTF-8',
        'From' => 'sales@connectpay.co.ss'
    ];
    
    wp_mail($email, $subject, $message, $headers);
}

/**
 * Create the custom_solution_requests table if it doesn't exist
 * This function should be called during plugin activation or setup
 */
function createCustomSolutionRequestsTable() {
    global $conn;
    
    $sql = "CREATE TABLE IF NOT EXISTS `custom_solution_requests` (
        `request_id` int NOT NULL AUTO_INCREMENT,
        `quote_number` varchar(50) NOT NULL UNIQUE,
        `user_id` int NOT NULL,
        `full_name` varchar(255) NOT NULL,
        `email` varchar(255) NOT NULL,
        `company_name` varchar(255) DEFAULT NULL,
        `phone` varchar(50) NOT NULL,
        `project_type` varchar(100) NOT NULL,
        `budget_range` varchar(50) DEFAULT NULL,
        `project_description` text NOT NULL,
        `additional_requirements` json DEFAULT NULL,
        `timeline` varchar(50) DEFAULT NULL,
        `referral_source` varchar(100) DEFAULT NULL,
        `package_id` varchar(50) DEFAULT NULL,
        `status` enum('PENDING','QUOTED','ACCEPTED','IN_PROGRESS','COMPLETED','CANCELLED') NOT NULL DEFAULT 'PENDING',
        `priority` enum('LOW','MEDIUM','HIGH','URGENT') NOT NULL DEFAULT 'MEDIUM',
        `assigned_to` int DEFAULT NULL,
        `quoted_amount` decimal(10,2) DEFAULT NULL,
        `quoted_at` timestamp NULL DEFAULT NULL,
        `accepted_at` timestamp NULL DEFAULT NULL,
        `completed_at` timestamp NULL DEFAULT NULL,
        `notes` text DEFAULT NULL,
        `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`request_id`),
        INDEX `idx_user_id` (`user_id`),
        INDEX `idx_status` (`status`),
        INDEX `idx_created_at` (`created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";
    
    $conn->query($sql);
}

/**
 * Create activity_logs table if it doesn't exist
 */
function createActivityLogsTable() {
    global $conn;
    
    $sql = "CREATE TABLE IF NOT EXISTS `activity_logs` (
        `log_id` bigint NOT NULL AUTO_INCREMENT,
        `user_id` int NOT NULL,
        `action` varchar(100) NOT NULL,
        `status` varchar(50) NOT NULL,
        `metadata` json DEFAULT NULL,
        `ip_address` varchar(45) DEFAULT NULL,
        `user_agent` varchar(500) DEFAULT NULL,
        `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`log_id`),
        INDEX `idx_user_id` (`user_id`),
        INDEX `idx_action` (`action`),
        INDEX `idx_created_at` (`created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";
    
    $conn->query($sql);
}

/**
 * Simple mail function wrapper (replace with proper email service)
 * @param string $to
 * @param string $subject
 * @param string $message
 * @param array $headers
 * @return bool
 */
function wp_mail($to, $subject, $message, $headers = []) {
    // For now, just log the email (replace with actual email service)
    error_log("EMAIL: To: {$to}, Subject: {$subject}");
    
    // TODO: Implement actual email sending using PHPMailer, SMTP, or email service API
    // For production, replace this with proper email implementation
    
    return true;
}

/**
 * Get statistics for custom solutions dashboard
 * @return array Statistics data
 */
function getCustomSolutionStats() {
    global $conn;
    
    $stats = [
        'total_requests' => 0,
        'pending_requests' => 0,
        'in_progress' => 0,
        'completed' => 0,
        'avg_completion_time' => 0
    ];
    
    try {
        // Total requests
        $result = $conn->query("SELECT COUNT(*) as count FROM custom_solution_requests");
        $stats['total_requests'] = $result->fetch_assoc()['count'];
        
        // Pending requests
        $result = $conn->query("SELECT COUNT(*) as count FROM custom_solution_requests WHERE status = 'PENDING'");
        $stats['pending_requests'] = $result->fetch_assoc()['count'];
        
        // In progress
        $result = $conn->query("SELECT COUNT(*) as count FROM custom_solution_requests WHERE status = 'IN_PROGRESS'");
        $stats['in_progress'] = $result->fetch_assoc()['count'];
        
        // Completed
        $result = $conn->query("SELECT COUNT(*) as count FROM custom_solution_requests WHERE status = 'COMPLETED'");
        $stats['completed'] = $result->fetch_assoc()['count'];
        
    } catch (Exception $e) {
        error_log("Error fetching custom solution stats: " . $e->getMessage());
    }
    
    return $stats;
}

/**
 * Initialize database tables for custom solutions
 * Call this function during setup or installation
 */
function initializeCustomSolutionsTables() {
    createCustomSolutionRequestsTable();
    createActivityLogsTable();
}

// Auto-initialize tables if they don't exist
if ($conn) {
    initializeCustomSolutionsTables();
}

?>