<?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') {
            $stmt = $db->query("
                SELECT p.id, p.sku, p.name, p.price, p.promo_price, p.status,
                       (SELECT image_path FROM product_images WHERE product_id = p.id ORDER BY is_main DESC, id ASC LIMIT 1) as main_image
                FROM products p 
                WHERE p.status = 'active' 
                ORDER BY p.id DESC
            ");
            $products = $stmt->fetchAll();
            api_response(true, "Products fetched successfully", $products);
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Add product API endpoint
            $name = trim($_POST['name'] ?? '');
            $price = floatval($_POST['price'] ?? 0);
            $sku = trim($_POST['sku'] ?? '');
            $category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;
            $description = trim($_POST['description'] ?? '');
            $promo_price = !empty($_POST['promo_price']) ? floatval($_POST['promo_price']) : null;
            $min_stock = intval($_POST['min_stock'] ?? 5);
            $purchase_type = trim($_POST['purchase_type'] ?? 'normal');

            if (empty($name) || $price <= 0) {
                api_response(false, "Product name and valid price are required", [], 400);
            }

            if (empty($sku)) {
                $sku = 'SKU-' . date('Ymd') . '-' . strtoupper(substr(md5(uniqid(rand(), true)), 0, 5));
            }

            try {
                $db->beginTransaction();

                $stmt = $db->prepare("
                    INSERT INTO products (user_id, category_id, sku, barcode, name, description, price, promo_price, min_stock, status, purchase_type) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?)
                ");
                $stmt->execute([
                    $_SESSION['user_id'] ?? 1,
                    $category_id,
                    $sku,
                    $sku,
                    $name,
                    $description,
                    $price,
                    $promo_price,
                    $min_stock,
                    $purchase_type
                ]);
                $product_id = $db->lastInsertId();

                // Save image to product_images table (product_id, image_path: uploads/products/filename, is_main = 1)
                $stmt_img = $db->prepare("INSERT INTO product_images (product_id, image_path, is_main) VALUES (?, ?, ?)");
                
                // 1. Check uploaded file in $_FILES
                $file = $_FILES['image'] ?? $_FILES['file'] ?? null;
                if ($file && $file['error'] === UPLOAD_ERR_OK) {
                    $upload_res = upload_image($file, 'products', 'prod');
                    if ($upload_res['success']) {
                        $image_path = 'uploads/products/' . $upload_res['filename'];
                        $stmt_img->execute([$product_id, $image_path, 1]);
                    }
                } elseif (!empty($_POST['image_path'])) {
                    // 2. Check path passed via POST
                    $raw_path = trim($_POST['image_path']);
                    $clean_path = (strpos($raw_path, 'uploads/products/') === 0) ? $raw_path : ('uploads/products/' . ltrim($raw_path, '/'));
                    $stmt_img->execute([$product_id, $clean_path, 1]);
                }

                // Initial Stock
                $initial_qty = intval($_POST['quantity'] ?? $_POST['stock'] ?? 10);
                $stmt_stock = $db->prepare("INSERT INTO product_stock (product_id, color_id, size_id, quantity) VALUES (?, null, null, ?)");
                $stmt_stock->execute([$product_id, $initial_qty]);

                $db->commit();
                api_response(true, "Product created successfully", [
                    'product_id' => $product_id,
                    'sku' => $sku,
                    'name' => $name
                ], 201);
            } catch (Exception $e) {
                $db->rollBack();
                api_response(false, "Failed to create product: " . $e->getMessage(), [], 500);
            }
        } else {
            api_response(false, "Method not allowed", [], 405);
        }
        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;
}
?>
