<?php
/**
 * Massage Controller for Zen Zone Spa API
 * Handles all massage session operations
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../utils/Response.php';
require_once __DIR__ . '/../utils/JWT.php';

class MassageController {
    
    private $db;
    
    public function __construct() {
        $this->db = DatabaseConfig::getConnection();
    }
    
    /**
     * Get therapist ID for a given user ID
     */
    private function getTherapistIdByUserId($userId) {
        $stmt = $this->db->prepare("SELECT id FROM therapists WHERE user_id = ?");
        $stmt->execute([$userId]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result['id'] ?? null;
    }
    
    /**
     * Get all massages with optional filtering and role-based access
     */
    public function getAllMassages() {
        try {
            // Get current user info from JWT
            $currentUserId = JWT::getCurrentUserId();
            $currentUserRole = JWT::getCurrentUserRole();
            
            $startDate = $_GET['start_date'] ?? null;
            $endDate = $_GET['end_date'] ?? null;
            $therapistId = $_GET['therapist_id'] ?? null;
            
            $sql = "SELECT 
                        m.id,
                        m.massage_type_id,
                        m.therapist_id,
                        m.client_id,
                        m.client_name,
                        m.amount,
                        m.duration,
                        m.therapist_commission,
                        m.net_income,
                        m.session_date,
                        m.status,
                        m.payment_method,
                        m.notes,
                        m.rating,
                        m.created_by,
                        m.created_at,
                        m.updated_at,
                        m.payment_sent_to_momo,
                        m.payment_verified,
                        m.payment_verified_at,
                        m.payment_verified_by,
                        m.payment_notes,
                        mt.name as massage_type,
                        t.name as therapist_name,
                        c.name as client_full_name,
                        c.phone as client_phone
                    FROM massages m
                    LEFT JOIN massage_types mt ON m.massage_type_id = mt.id
                    LEFT JOIN therapists t ON m.therapist_id = t.id
                    LEFT JOIN clients c ON m.client_id = c.id
                    WHERE 1=1";
            
            $params = [];
            
            // Role-based filtering: Therapists only see their own sessions
            if ($currentUserRole === 'therapist') {
                $userTherapistId = $this->getTherapistIdByUserId($currentUserId);
                if ($userTherapistId) {
                    $sql .= " AND m.therapist_id = :user_therapist_id";
                    $params['user_therapist_id'] = $userTherapistId;
                } else {
                    // Therapist user but no linked therapist record - return empty
                    Response::success(['massages' => [], 'count' => 0], 'No sessions found');
                    return;
                }
            }
            // Admin and manager see all sessions
            
            if ($startDate) {
                $sql .= " AND DATE(m.session_date) >= :start_date";
                $params['start_date'] = $startDate;
            }
            
            if ($endDate) {
                $sql .= " AND DATE(m.session_date) <= :end_date";
                $params['end_date'] = $endDate;
            }
            
            if ($therapistId) {
                $sql .= " AND m.therapist_id = :therapist_id";
                $params['therapist_id'] = $therapistId;
            }
            
            $sql .= " ORDER BY m.session_date DESC, m.created_at DESC";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            $massages = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            Response::success([
                'massages' => $massages,
                'count' => count($massages)
            ], 'Massages retrieved successfully');
            
        } catch (Exception $e) {
            error_log("Get massages error: " . $e->getMessage());
            Response::serverError('Failed to fetch massages');
        }
    }
    
    /**
     * Get a specific massage by ID
     */
    public function getMassage($id) {
        try {
            $sql = "SELECT 
                        m.*,
                        mt.name as massage_type,
                        mt.description as massage_description,
                        t.name as therapist_name,
                        t.phone as therapist_phone,
                        c.name as client_full_name,
                        c.email as client_email,
                        c.phone as client_phone
                    FROM massages m
                    LEFT JOIN massage_types mt ON m.massage_type_id = mt.id
                    LEFT JOIN therapists t ON m.therapist_id = t.id
                    LEFT JOIN clients c ON m.client_id = c.id
                    WHERE m.id = ?";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute([$id]);
            $massage = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$massage) {
                Response::notFound('Massage session not found');
            }
            
            Response::success($massage, 'Massage retrieved successfully');
            
        } catch (Exception $e) {
            error_log("Get massage error: " . $e->getMessage());
            Response::serverError('Failed to fetch massage');
        }
    }
    
    /**
     * Create a new massage session
     */
    public function createMassage($input) {
        try {
            // Validate required fields
            $errors = Response::validateRequired($input, [
                'massage_type_id', 'therapist_id', 'amount', 'session_date'
            ]);
            if ($errors) {
                Response::validationError($errors);
            }
            
            // Optional: client_name for walk-ins or client_id for registered clients
            if (!isset($input['client_id']) && !isset($input['client_name'])) {
                Response::error('Either client_id or client_name is required', 400);
            }
            
            // Get current user ID from JWT
            $currentUserId = JWT::getCurrentUserId() ?? 1;
            
            $sql = "INSERT INTO massages (
                        massage_type_id, therapist_id, client_id, client_name,
                        amount, duration, session_date, status, payment_method,
                        notes, created_by,
                        payment_sent_to_momo, payment_notes
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute([
                $input['massage_type_id'],
                $input['therapist_id'],
                $input['client_id'] ?? null,
                $input['client_name'] ?? null,
                $input['amount'],
                $input['duration'] ?? 60,
                $input['session_date'],
                $input['status'] ?? 'completed',
                $input['payment_method'] ?? 'cash',
                $input['notes'] ?? null,
                $currentUserId,
                isset($input['payment_sent_to_momo']) ? (int)(bool)$input['payment_sent_to_momo'] : 0,
                $input['payment_notes'] ?? null
            ]);
            
            if ($result) {
                $massageId = $this->db->lastInsertId();
                $this->getMassage($massageId);
            } else {
                Response::serverError('Failed to create massage session');
            }
            
        } catch (Exception $e) {
            error_log("Create massage error: " . $e->getMessage());
            Response::serverError('Failed to create massage session');
        }
    }
    
    /**
     * Update an existing massage
     */
    public function updateMassage($id, $input) {
        try {
            // Check if massage exists
            $stmt = $this->db->prepare("SELECT id FROM massages WHERE id = ?");
            $stmt->execute([$id]);
            if (!$stmt->fetch()) {
                Response::notFound('Massage session not found');
            }
            
            // Build update query dynamically
            $updateFields = [];
            $params = [];
            
            $allowedFields = [
                'massage_type_id', 'therapist_id', 'client_id', 'client_name',
                'amount', 'duration', 'session_date', 'status', 'payment_method',
                'notes', 'rating'
            ];
            
            foreach ($allowedFields as $field) {
                if (isset($input[$field])) {
                    $updateFields[] = "$field = ?";
                    $params[] = $input[$field];
                }
            }
            
            if (empty($updateFields)) {
                Response::error('No valid fields to update', 400);
            }
            
            $params[] = $id; // Add ID for WHERE clause
            $sql = "UPDATE massages SET " . implode(', ', $updateFields) . " WHERE id = ?";
            
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute($params);
            
            if ($result) {
                $this->getMassage($id);
            } else {
                Response::serverError('Failed to update massage session');
            }
            
        } catch (Exception $e) {
            error_log("Update massage error: " . $e->getMessage());
            Response::serverError('Failed to update massage session');
        }
    }
    
    /**
     * Delete a massage session
     */
    public function deleteMassage($id) {
        try {
            // Check if massage exists
            $stmt = $this->db->prepare("SELECT id FROM massages WHERE id = ?");
            $stmt->execute([$id]);
            if (!$stmt->fetch()) {
                Response::notFound('Massage session not found');
            }
            
            // Delete the massage
            $stmt = $this->db->prepare("DELETE FROM massages WHERE id = ?");
            $result = $stmt->execute([$id]);
            
            if ($result) {
                Response::success(null, 'Massage session deleted successfully');
            } else {
                Response::serverError('Failed to delete massage session');
            }
            
        } catch (Exception $e) {
            error_log("Delete massage error: " . $e->getMessage());
            Response::serverError('Failed to delete massage session');
        }
    }
    
    /**
     * Get available therapists
     */
    public function getTherapists() {
        try {
            $sql = "SELECT id, name, email, phone, specialties, is_active 
                    FROM therapists 
                    WHERE is_active = 1 
                    ORDER BY name ASC";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute();
            $therapists = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Decode JSON specialties
            foreach ($therapists as &$therapist) {
                if ($therapist['specialties']) {
                    $therapist['specialties'] = json_decode($therapist['specialties'], true);
                }
            }
            
            Response::success($therapists, 'Therapists retrieved successfully');
            
        } catch (Exception $e) {
            error_log("Get therapists error: " . $e->getMessage());
            Response::serverError('Failed to fetch therapists');
        }
    }
    
    /**
     * Get massage types
     */
    public function getMassageTypes() {
        try {
            $sql = "SELECT id, name, description, base_duration, base_price, category, is_active 
                    FROM massage_types 
                    WHERE is_active = 1 
                    ORDER BY category ASC, name ASC";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute();
            $types = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            Response::success($types, 'Massage types retrieved successfully');
            
        } catch (Exception $e) {
            error_log("Get massage types error: " . $e->getMessage());
            Response::serverError('Failed to fetch massage types');
        }
    }
    
    /**
     * Get pending MoMo payments for follow-up (Admin only)
     * Shows sessions where payment_sent_to_momo = true but payment_verified = false
     */
    public function getPendingMomoPayments() {
        try {
            // Only admin can access this
            $currentUserRole = JWT::getCurrentUserRole();
            if ($currentUserRole !== 'admin') {
                Response::forbidden('Admin access required');
                return;
            }
            
            $sql = "SELECT 
                        m.id,
                        m.massage_type_id,
                        m.therapist_id,
                        m.client_name,
                        m.amount,
                        m.session_date,
                        m.payment_method,
                        m.payment_sent_to_momo,
                        m.payment_verified,
                        m.payment_notes,
                        mt.name as massage_type,
                        t.name as therapist_name,
                        t.phone as therapist_phone,
                        DATEDIFF(CURDATE(), DATE(m.session_date)) as days_ago
                    FROM massages m
                    LEFT JOIN massage_types mt ON m.massage_type_id = mt.id
                    LEFT JOIN therapists t ON m.therapist_id = t.id
                    WHERE m.payment_sent_to_momo = TRUE 
                    AND m.payment_verified = FALSE
                    AND m.payment_method = 'mobile_money'
                    ORDER BY m.session_date DESC";
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute();
            $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            Response::success([
                'pending_payments' => $payments,
                'count' => count($payments)
            ], 'Pending MoMo payments retrieved successfully');
            
        } catch (Exception $e) {
            error_log("Get pending MoMo payments error: " . $e->getMessage());
            Response::serverError('Failed to fetch pending payments');
        }
    }
    
    /**
     * Verify MoMo payment (Admin only)
     * Marks a payment as verified
     */
    public function verifyMomoPayment($massageId, $input) {
        try {
            // Only admin can verify payments
            $currentUserRole = JWT::getCurrentUserRole();
            $currentUserId = JWT::getCurrentUserId();
            
            if ($currentUserRole !== 'admin') {
                Response::forbidden('Admin access required');
                return;
            }
            
            $sql = "UPDATE massages 
                    SET payment_verified = TRUE,
                        payment_verified_at = NOW(),
                        payment_verified_by = ?,
                        payment_notes = ?
                    WHERE id = ?";
            
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute([
                $currentUserId,
                $input['payment_notes'] ?? null,
                $massageId
            ]);
            
            if ($result) {
                $this->getMassage($massageId);
            } else {
                Response::serverError('Failed to verify payment');
            }
            
        } catch (Exception $e) {
            error_log("Verify MoMo payment error: " . $e->getMessage());
            Response::serverError('Failed to verify payment');
        }
    }
} 