<?php
// Consolidated API endpoints
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-API-Token');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { 
    exit; 
}

require_once __DIR__ . '/../../inc/db.php';
require_once __DIR__ . '/../../inc/functions.php';

// Get the endpoint from URL
$request_uri = $_SERVER['REQUEST_URI'];
$path = parse_url($request_uri, PHP_URL_PATH);
$path_parts = explode('/', trim($path, '/'));
$endpoint = end($path_parts);

// Get query parameters
$action = $_GET['action'] ?? '';

// Enhanced token detection function
function get_api_token() {
    $token = '';
    
    // Method 1: Authorization header (Bearer token)
    if (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
        if (preg_match('/Bearer\s+(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $m)) {
            $token = $m[1];
        }
    }
    
    // Method 2: GET parameter
    if (!$token && isset($_GET['token']) && !empty($_GET['token'])) {
        $token = $_GET['token'];
    }
    
    // Method 3: POST data
    if (!$token) {
        $postData = get_post_data();
        if (isset($postData['token']) && !empty($postData['token'])) {
            $token = $postData['token'];
        }
    }
    
    // Method 4: Custom header
    if (!$token && function_exists('apache_request_headers')) {
        $headers = apache_request_headers();
        if (isset($headers['X-API-Token']) && !empty($headers['X-API-Token'])) {
            $token = $headers['X-API-Token'];
        }
    }
    
    return $token;
}

// Validate token function
function validate_token($conn) {
    $token = get_api_token();
    
    if (!$token) {
        send_json([
            'status' => false,
            'msg' => 'Missing API token',
            'debug' => [
                'method' => $_SERVER['REQUEST_METHOD'],
                'has_auth_header' => !empty($_SERVER['HTTP_AUTHORIZATION']),
                'has_get_token' => isset($_GET['token']),
                'has_post_data' => !empty($_POST),
                'suggestions' => [
                    'Add ?token=YOUR_TOKEN to URL',
                    'Send Authorization: Bearer YOUR_TOKEN header',
                    'Send X-API-Token: YOUR_TOKEN header',
                    'Include token in POST/JSON body'
                ]
            ]
        ]);
    }
    
    $stmt = $conn->prepare("SELECT id, name, email FROM users WHERE api_token = ?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    
    if (!$user) {
        send_json(['status' => false, 'msg' => 'Invalid token']);
    }
    
    return $user;
}

// Route to appropriate endpoint
switch ($endpoint) {
    case 'login':
        handle_login();
        break;
    case 'register':
        handle_register();
        break;
    case 'products':
        handle_products();
        break;
    case 'newproduct':
        handle_newproduct();
        break;
    case 'profile':
        handle_profile();
        break;
    case 'logout':
        handle_logout();
        break;
    default:
        send_json(['status' => false, 'msg' => 'Endpoint not found']);
}

// Login endpoint
function handle_login() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        send_json(['status' => false, 'msg' => 'Method not allowed']);
    }
    
    $data = get_post_data();
    $email = trim($data['email'] ?? '');
    $password = $data['password'] ?? '';
    
    if (!$email || !$password) {
        send_json(['status' => false, 'msg' => 'Email and password required']);
    }
    
    $stmt = $conn->prepare("SELECT id, name, password FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();
    $user = $res->fetch_assoc();
    $stmt->close();
    
    if ($user && password_verify($password, $user['password'])) {
        // Generate new token and save
        $token = create_api_token(32);
        $upd = $conn->prepare("UPDATE users SET api_token = ? WHERE id = ?");
        $upd->bind_param("si", $token, $user['id']);
        $upd->execute();
        $upd->close();
        
        send_json([
            'status' => true,
            'msg' => 'Login successful',
            'data' => [
                'id' => $user['id'],
                'name' => $user['name'],
                'email' => $email,
                'api_token' => $token
            ]
        ]);
    } else {
        send_json(['status' => false, 'msg' => 'Invalid email or password']);
    }
}

// Register endpoint
function handle_register() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        send_json(['status' => false, 'msg' => 'Method not allowed']);
    }
    
    $data = get_post_data();
    $name = trim($data['name'] ?? '');
    $email = trim($data['email'] ?? '');
    $password = $data['password'] ?? '';
    $confirm = $data['confirm_password'] ?? $data['confirm'] ?? '';
    
    if (!$name || !$email || !$password || !$confirm) {
        send_json(['status' => false, 'msg' => 'All fields are required']);
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        send_json(['status' => false, 'msg' => 'Invalid email']);
    }
    if ($password !== $confirm) {
        send_json(['status' => false, 'msg' => 'Password and confirm password do not match']);
    }
    
    // Check if email exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        send_json(['status' => false, 'msg' => 'Email already registered']);
    }
    $stmt->close();
    
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $token = create_api_token(32);
    
    $stmt = $conn->prepare("INSERT INTO users (name, email, password, api_token) VALUES (?,?,?,?)");
    $stmt->bind_param("ssss", $name, $email, $hash, $token);
    if ($stmt->execute()) {
        $insert_id = $stmt->insert_id;
        send_json([
            'status' => true,
            'msg' => 'Registration successful',
            'data' => [
                'id' => $insert_id,
                'name' => $name,
                'email' => $email,
                'api_token' => $token
            ]
        ]);
    } else {
        send_json(['status' => false, 'msg' => 'Registration failed', 'error' => $conn->error]);
    }
}

// Products endpoint (GET all products)
function handle_products() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        send_json(['status' => false, 'msg' => 'Method not allowed']);
    }
    
    // Validate token
    validate_token($conn);
    
    // Fetch all products
    $products = [];
    $result = $conn->query("SELECT * FROM products ORDER BY id ASC");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $row['images'] = json_decode($row['images'], true); // decode JSON column
            $products[] = $row;
        }
    }
    
    // Output JSON
    send_json([
        'status' => true,
        'msg' => 'Product list fetched',
        'products' => $products
    ]);
}

// New product endpoint (GET all products - same as products but with enhanced token detection)
function handle_newproduct() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        send_json(['status' => false, 'msg' => 'Method not allowed']);
    }
    
    // Enhanced token detection
    $token = get_api_token();
    
    if (!$token) {
        send_json([
            'status' => false,
            'msg' => 'Missing API token',
            'debug' => [
                'method' => $_SERVER['REQUEST_METHOD'],
                'has_auth_header' => !empty($_SERVER['HTTP_AUTHORIZATION']),
                'has_get_token' => isset($_GET['token']),
                'has_post_data' => !empty($_POST),
                'suggestions' => [
                    'Add ?token=YOUR_TOKEN to URL',
                    'Send Authorization: Bearer YOUR_TOKEN header',
                    'Send X-API-Token: YOUR_TOKEN header',
                    'Include token in POST/JSON body'
                ]
            ]
        ]);
    }
    
    $stmt = $conn->prepare("SELECT id FROM users WHERE api_token = ?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    
    if (!$user) {
        send_json(['status' => false, 'msg' => 'Invalid token']);
    }
    
    // Fetch all products
    $products = [];
    $result = $conn->query("SELECT * FROM products ORDER BY id ASC");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $row['images'] = json_decode($row['images'], true); // decode JSON column
            $products[] = $row;
        }
    }
    
    // Output JSON
    send_json([
        'status' => true,
        'msg' => 'Product list fetched',
        'products' => $products
    ]);
}

// Profile endpoint
function handle_profile() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        send_json(['status' => false, 'msg' => 'Method not allowed']);
    }
    
    // Validate token and get user info
    $user = validate_token($conn);
    
    send_json([
        'status' => true,
        'msg' => 'Profile retrieved successfully',
        'data' => [
            'id' => $user['id'],
            'name' => $user['name'],
            'email' => $user['email']
        ]
    ]);
}

// Logout endpoint
function handle_logout() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        send_json(['status' => false, 'msg' => 'Method not allowed']);
    }
    
    // Validate token
    $user = validate_token($conn);
    
    // Clear the token
    $stmt = $conn->prepare("UPDATE users SET api_token = NULL WHERE id = ?");
    $stmt->bind_param("i", $user['id']);
    $stmt->execute();
    $stmt->close();
    
    send_json([
        'status' => true,
        'msg' => 'Logout successful'
    ]);
}
?>
