<?php
/**
 * REST API Controller
 * CMTC Shopping
 */
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../functions/helpers.php';

$database = new Database();
$db = $database->getConnection();

$route = $_GET['route'] ?? '';

// Simple Token-based Auth validation
function validate_token($db) {
    $headers = getallheaders();
    $auth_header = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) {
        $token = $matches[1];
        // Decode token. Format: base64(username:user_id)
        $decoded = base64_decode($token);
        if ($decoded) {
            $parts = explode(':', $decoded);
            if (count($parts) === 2) {
                $username = $parts[0];
                $user_id = intval($parts[1]);
                
                // Confirm against DB
                $stmt = $db->prepare("SELECT id, username, role_id FROM users WHERE id = ? AND username = ? AND status = 'active' LIMIT 1");
                $stmt->execute([$user_id, $username]);
                $user = $stmt->fetch();
                if ($user) {
                    return $user;
                }
            }
        }
    }
    return false;
}

// Route Router
switch ($route) {
    case 'login':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            api_response(false, "Method not allowed", [], 405);
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        $username = trim($input['username'] ?? '');
        $password = $input['password'] ?? '';
        
        if (empty($username) || empty($password)) {
            api_response(false, "Username and password required", [], 400);
        }
        
        $stmt = $db->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
        $stmt->execute([$username]);
        $user = $stmt->fetch();
        
        if ($user && password_verify($password, $user['password'])) {
            if ($user['status'] !== 'active') {
                api_response(false, "Account is disabled", [], 403);
            }
            
            // Generate a simple token: base64(username:user_id)
            $token = base64_encode($user['username'] . ':' . $user['id']);
            
            api_response(true, "Authentication successful", [
                'token' => $token,
                'user' => [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'firstname' => $user['firstname'],
                    'lastname' => $user['lastname'],
                    'email' => $user['email'],
                    'role_id' => $user['role_id']
                ]
            ]);
        } else {
            api_response(false, "Invalid credentials", [], 401);
        }
        break;

    case 'products':
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            api_response(false, "Method not allowed", [], 405);
        }
        
        $stmt = $db->query("SELECT id, sku, name, price, promo_price, status FROM products WHERE status = 'active' ORDER BY id DESC");
        $products = $stmt->fetchAll();
        api_response(true, "Products fetched successfully", $products);
        break;

    case 'orders':
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            api_response(false, "Method not allowed", [], 405);
        }
        
        $user = validate_token($db);
        if (!$user) {
            api_response(false, "Unauthorized", [], 401);
        }
        
        $stmt = $db->prepare("SELECT id, order_no, total_amount, net_amount, status, created_at FROM orders WHERE user_id = ? ORDER BY id DESC");
        $stmt->execute([$user['id']]);
        $orders = $stmt->fetchAll();
        
        api_response(true, "Orders fetched successfully", $orders);
        break;

    case 'profile':
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            api_response(false, "Method not allowed", [], 405);
        }
        
        $user = validate_token($db);
        if (!$user) {
            api_response(false, "Unauthorized", [], 401);
        }
        
        // Fetch detailed profile
        $stmt = $db->prepare("
            SELECT u.id, u.username, u.prefix, u.firstname, u.lastname, u.email, u.phone, u.avatar, 
                   r.name as role_name, d.name as department_name, u.created_at
            FROM users u
            JOIN user_roles r ON u.role_id = r.id
            LEFT JOIN departments d ON u.department_id = d.id
            WHERE u.id = ?
            LIMIT 1
        ");
        $stmt->execute([$user['id']]);
        $profile = $stmt->fetch();
        
        api_response(true, "Profile fetched successfully", $profile);
        break;

    case 'get_ai_recommendations':
        $gender = $_POST['gender'] ?? 'female';
        $occasion = $_POST['occasion'] ?? 'wedding';
        $size = $_POST['size'] ?? 'M';
        
        // Build dynamic search patterns
        $gender_keywords = [];
        if ($gender === 'female') {
            $gender_keywords = ['สตรี', 'หญิง', 'เดรส', 'ราตรี', 'กระโปรง', 'dress', 'skirt', 'lady', 'woman'];
        } elseif ($gender === 'male') {
            $gender_keywords = ['บุรุษ', 'ชาย', 'สูท', 'คอปก', 'เชิ้ต', 'กางเกง', 'suit', 'shirt', 'men', 'man'];
        }
        
        $occasion_keywords = [];
        if ($occasion === 'wedding') {
            $occasion_keywords = ['แต่งงาน', 'วิวาห์', 'wedding', 'เจ้าสาว', 'เจ้าบ่าว', 'เพื่อนเจ้าสาว'];
        } elseif ($occasion === 'gala') {
            $occasion_keywords = ['ราตรี', 'กาล่า', 'gala', 'หรู', 'premium', 'luxury'];
        } elseif ($occasion === 'party') {
            $occasion_keywords = ['ปาร์ตี้', 'สังสรรค์', 'party', 'เลื่อม', 'ฉลอง'];
        } elseif ($occasion === 'casual') {
            $occasion_keywords = ['ทำงาน', 'สุภาพ', 'casual', 'เที่ยว', 'สบาย'];
        }

        // Fetch active products
        $sql = "SELECT p.*, c.name as category_name, 
                      (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY is_main DESC, id ASC LIMIT 1) as main_image,
                      (SELECT GROUP_CONCAT(size_name) FROM product_sizes WHERE product_id = p.id) as sizes
               FROM products p
               LEFT JOIN categories c ON p.category_id = c.id
               WHERE p.status = 'active'";
               
        $stmt = $db->query($sql);
        $all_products = $stmt->fetchAll();
        
        $recommended = [];
        foreach ($all_products as $prod) {
            $score = 0;
            $name_desc = mb_strtolower($prod['name'] . ' ' . $prod['description'] . ' ' . ($prod['category_name'] ?? ''));
            
            // Score based on gender
            foreach ($gender_keywords as $kw) {
                if (mb_strpos($name_desc, mb_strtolower($kw)) !== false) {
                    $score += 5;
                }
            }
            
            // Score based on occasion
            foreach ($occasion_keywords as $kw) {
                if (mb_strpos($name_desc, mb_strtolower($kw)) !== false) {
                    $score += 8;
                }
            }
            
            // Match size (bonus score if the recommended size is available)
            if (!empty($prod['sizes'])) {
                $prod_sizes = array_map('trim', explode(',', mb_strtoupper($prod['sizes'])));
                if (in_array(mb_strtoupper($size), $prod_sizes)) {
                    $score += 10;
                }
            }
            
            $prod['match_score'] = $score;
            $recommended[] = $prod;
        }
        
        // Sort by score descending, limit to 6 products
        usort($recommended, function($a, $b) {
            return $b['match_score'] <=> $a['match_score'];
        });
        
        $recommended = array_slice($recommended, 0, 6);
        
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'data' => $recommended]);
        exit();

    case 'upload':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            api_response(false, "Method not allowed", [], 405);
        }
        
        $type = $_POST['type'] ?? 'products';
        $allowed_types = ['products', 'news', 'slips', 'avatars', 'general'];
        if (!in_array($type, $allowed_types)) {
            $type = 'products';
        }

        if (!isset($_FILES['file']) && !isset($_FILES['image'])) {
            api_response(false, "No file uploaded (use 'file' or 'image' field)", [], 400);
        }

        $file = $_FILES['file'] ?? $_FILES['image'];
        $prefix = ($type === 'products') ? 'prod' : substr($type, 0, 4);
        $result = upload_image($file, $type, $prefix);

        if ($result['success']) {
            api_response(true, "Image uploaded successfully", [
                'filename' => $result['filename'],
                'path' => $result['relative_path'],
                'url' => $result['url']
            ]);
        } else {
            api_response(false, $result['error'], [], 400);
        }
        break;

    default:
        api_response(false, "API route not found", [], 404);
        break;
}
?>
