<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../utils/Response.php';
require_once __DIR__ . '/../utils/ValidationHelper.php';

class ContactController {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }
    
    /**
     * Handle contact form submission
     * POST /api/contact
     */
    public function submitContact() {
        try {
            // Validate request method
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                return Response::error('Method not allowed', 405);
            }
            
            // Get and validate input data
            $data = $this->getInputData();
            $validation = $this->validateContactData($data);
            
            if (!$validation['isValid']) {
                return Response::validationError($validation['errors']);
            }
            
            // Save to database
            $contactId = $this->saveContactInquiry($data);
            
            if ($contactId) {
                // Send notification (you can implement email notification here)
                $this->sendNotification($data);
                
                return Response::success([
                    'message' => 'Contact inquiry submitted successfully',
                    'inquiry_id' => $contactId
                ], 'Contact inquiry submitted successfully', 201);
            } else {
                return Response::serverError('Failed to save contact inquiry');
            }
            
        } catch (Exception $e) {
            error_log("Contact submission error: " . $e->getMessage());
            return Response::serverError('Internal server error');
        }
    }
    
    /**
     * Get all contact inquiries (for admin/mobile app)
     * GET /api/contact/inquiries
     */
    public function getInquiries() {
        try {
            // Check authentication (you might want to add JWT verification)
            // $this->requireAuth();
            
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $limit = isset($_GET['limit']) ? min((int)$_GET['limit'], 100) : 20;
            $offset = ($page - 1) * $limit;
            
            $status = isset($_GET['status']) ? $_GET['status'] : null;
            $service = isset($_GET['service']) ? $_GET['service'] : null;
            
            // Build query
            $whereClause = '';
            $params = [];
            
            if ($status) {
                $whereClause .= " WHERE status = ?";
                $params[] = $status;
            }
            
            if ($service) {
                $whereClause .= ($whereClause ? " AND" : " WHERE") . " service = ?";
                $params[] = $service;
            }
            
            // Get total count
            $countQuery = "SELECT COUNT(*) as total FROM contact_inquiries" . $whereClause;
            $countStmt = $this->db->prepare($countQuery);
            if ($params) {
                $countStmt->execute($params);
            } else {
                $countStmt->execute();
            }
            $totalCount = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
            
            // Get inquiries
            $query = "
                SELECT 
                    ci.*,
                    u.name as assigned_user_name
                FROM contact_inquiries ci
                LEFT JOIN users u ON ci.assigned_to = u.id
                $whereClause
                ORDER BY ci.created_at DESC
                LIMIT ? OFFSET ?
            ";
            
            $stmt = $this->db->prepare($query);
            $params[] = $limit;
            $params[] = $offset;
            $stmt->execute($params);
            
            $inquiries = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            return Response::paginated($inquiries, $totalCount, $page, $limit, 'Contact inquiries retrieved successfully');
            
        } catch (Exception $e) {
            error_log("Get inquiries error: " . $e->getMessage());
            return Response::serverError('Internal server error');
        }
    }
    
    /**
     * Get single contact inquiry
     * GET /api/contact/inquiries/{id}
     */
    public function getInquiry($id) {
        try {
            $query = "
                SELECT 
                    ci.*,
                    u.name as assigned_user_name
                FROM contact_inquiries ci
                LEFT JOIN users u ON ci.assigned_to = u.id
                WHERE ci.id = ?
            ";
            
            $stmt = $this->db->prepare($query);
            $stmt->execute([$id]);
            
            $inquiry = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$inquiry) {
                return Response::notFound('Contact inquiry not found');
            }
            
            return Response::success(['inquiry' => $inquiry], 'Contact inquiry retrieved successfully');
            
        } catch (Exception $e) {
            error_log("Get inquiry error: " . $e->getMessage());
            return Response::serverError('Internal server error');
        }
    }
    
    /**
     * Update contact inquiry status
     * PUT /api/contact/inquiries/{id}
     */
    public function updateInquiry($id) {
        try {
            $data = $this->getInputData();
            
            $allowedFields = ['status', 'priority', 'notes', 'assigned_to', 'responded_at'];
            $updateFields = [];
            $params = [];
            
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updateFields[] = "$field = ?";
                    $params[] = $data[$field];
                }
            }
            
            if (empty($updateFields)) {
                return Response::error('No valid fields to update', 400);
            }
            
            $updateFields[] = "updated_at = NOW()";
            $params[] = $id;
            
            $query = "UPDATE contact_inquiries SET " . implode(', ', $updateFields) . " WHERE id = ?";
            $stmt = $this->db->prepare($query);
            $result = $stmt->execute($params);
            
            if ($result && $stmt->rowCount() > 0) {
                return Response::success(['message' => 'Contact inquiry updated successfully'], 'Contact inquiry updated successfully');
            } else {
                return Response::notFound('Contact inquiry not found or no changes made');
            }
            
        } catch (Exception $e) {
            error_log("Update inquiry error: " . $e->getMessage());
            return Response::serverError('Internal server error');
        }
    }
    
    /**
     * Get contact statistics for dashboard
     * GET /api/contact/stats
     */
    public function getContactStats() {
        try {
            $query = "
                SELECT 
                    COUNT(*) as total_inquiries,
                    COUNT(CASE WHEN status = 'new' THEN 1 END) as new_inquiries,
                    COUNT(CASE WHEN status = 'contacted' THEN 1 END) as contacted_inquiries,
                    COUNT(CASE WHEN status = 'converted' THEN 1 END) as converted_inquiries,
                    COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN 1 END) as today_inquiries,
                    COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as week_inquiries,
                    COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as month_inquiries
                FROM contact_inquiries
            ";
            
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            $stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Get service breakdown
            $serviceQuery = "
                SELECT 
                    service,
                    COUNT(*) as count
                FROM contact_inquiries 
                WHERE service IS NOT NULL AND service != ''
                GROUP BY service
                ORDER BY count DESC
            ";
            
            $serviceStmt = $this->db->prepare($serviceQuery);
            $serviceStmt->execute();
            $serviceBreakdown = $serviceStmt->fetchAll(PDO::FETCH_ASSOC);
            
            return Response::success([
                'stats' => $stats,
                'service_breakdown' => $serviceBreakdown
            ], 'Contact statistics retrieved successfully');
            
        } catch (Exception $e) {
            error_log("Get contact stats error: " . $e->getMessage());
            return Response::serverError('Internal server error');
        }
    }
    
    /**
     * Get input data from request
     */
    private function getInputData() {
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
        
        if (strpos($contentType, 'application/json') !== false) {
            $input = file_get_contents('php://input');
            return json_decode($input, true) ?: [];
        }
        
        return $_POST;
    }
    
    /**
     * Validate contact form data
     */
    private function validateContactData($data) {
        $errors = [];
        
        // Required fields
        if (empty($data['name'])) {
            $errors['name'] = 'Name is required';
        } elseif (strlen($data['name']) > 100) {
            $errors['name'] = 'Name must be less than 100 characters';
        }
        
        if (empty($data['email'])) {
            $errors['email'] = 'Email is required';
        } elseif (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Invalid email format';
        } elseif (strlen($data['email']) > 150) {
            $errors['email'] = 'Email must be less than 150 characters';
        }
        
        // Optional but validated fields
        if (!empty($data['phone']) && strlen($data['phone']) > 20) {
            $errors['phone'] = 'Phone number must be less than 20 characters';
        }
        
        if (!empty($data['service']) && strlen($data['service']) > 50) {
            $errors['service'] = 'Service must be less than 50 characters';
        }
        
        if (!empty($data['message']) && strlen($data['message']) > 1000) {
            $errors['message'] = 'Message must be less than 1000 characters';
        }
        
        return [
            'isValid' => empty($errors),
            'errors' => $errors
        ];
    }
    
    /**
     * Save contact inquiry to database
     */
    private function saveContactInquiry($data) {
        try {
            $query = "
                INSERT INTO contact_inquiries (name, email, phone, service, message, source) 
                VALUES (?, ?, ?, ?, ?, ?)
            ";
            
            $stmt = $this->db->prepare($query);
            $result = $stmt->execute([
                $data['name'],
                $data['email'],
                $data['phone'] ?? null,
                $data['service'] ?? null,
                $data['message'] ?? null,
                $data['source'] ?? 'website'
            ]);
            
            return $result ? $this->db->lastInsertId() : false;
            
        } catch (Exception $e) {
            error_log("Save contact inquiry error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Send notification about new contact inquiry
     */
    private function sendNotification($data) {
        // TODO: Implement email notification to spa staff
        // You can integrate with PHPMailer or any email service
        
        // For now, just log the notification
        error_log("New contact inquiry from: " . $data['name'] . " (" . $data['email'] . ")");
        
        // Example: Send email to spa management
        /*
        $to = 'zenzonerw@gmail.com';
        $subject = 'New Contact Inquiry - Zen Zone Spa';
        $message = "New contact inquiry received:\n\n";
        $message .= "Name: " . $data['name'] . "\n";
        $message .= "Email: " . $data['email'] . "\n";
        $message .= "Phone: " . ($data['phone'] ?? 'Not provided') . "\n";
        $message .= "Service: " . ($data['service'] ?? 'Not specified') . "\n";
        $message .= "Message: " . ($data['message'] ?? 'No message') . "\n";
        
        mail($to, $subject, $message);
        */
    }
}
