<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../credentials.php';

dm_require_admin();

$input  = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $input['action'] ?? $_GET['action'] ?? 'test';
$client_id = (int)($input['client_id'] ?? $_GET['client_id'] ?? 0);

if (!$client_id) { echo json_encode(['ok'=>false,'error'=>'client_id requerido']); exit; }
dm_require_client_access($client_id);

$creds = dm_get_credentials($client_id, 'shopify');
$shop_domain  = trim($creds['shop_domain']  ?? '');
$access_token = trim($creds['access_token'] ?? '');

if (!$shop_domain || !$access_token) {
    echo json_encode(['ok'=>false,'error'=>'Configura el dominio y el Access Token de Shopify en APIs → Shopify']);
    exit;
}

$shop_domain = str_replace(['https://','http://'], '', $shop_domain);
$shop_domain = rtrim($shop_domain, '/');
if (!str_contains($shop_domain, '.')) $shop_domain .= '.myshopify.com';
if (!str_contains($shop_domain, 'myshopify.com') && !str_contains($shop_domain, '.')) {
    $shop_domain .= '.myshopify.com';
}

$api_ver = '2024-04';

function shopify_req(string $shop, string $token, string $method, string $endpoint, array $body = []): array {
    $url = "https://{$shop}/admin/api/2024-04/{$endpoint}";
    $ch  = curl_init($url);
    $headers = [
        'Content-Type: application/json',
        'X-Shopify-Access-Token: ' . $token,
    ];
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    if ($body && in_array($method, ['POST','PUT','PATCH'])) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_errno($ch);
    curl_close($ch);
    if ($err) return ['ok'=>false,'error'=>"curl error #{$err}",'code'=>0];
    $data = json_decode($resp, true) ?? [];
    if ($code >= 400) {
        $msg = $data['errors'] ?? ($data['error'] ?? "HTTP {$code}");
        if (is_array($msg)) $msg = implode('; ', array_map(fn($k,$v)=>"$k: ".(is_array($v)?implode(',',$v):$v), array_keys($msg), $msg));
        return ['ok'=>false,'error'=>$msg,'code'=>$code,'raw'=>$resp];
    }
    return ['ok'=>true,'data'=>$data,'code'=>$code];
}

switch ($action) {

    case 'test':
        $r = shopify_req($shop_domain, $access_token, 'GET', 'shop.json');
        if (!$r['ok']) { echo json_encode(['ok'=>false,'error'=>'Error conectando con Shopify: '.$r['error']]); exit; }
        $shop = $r['data']['shop'] ?? [];
        echo json_encode(['ok'=>true,'shop_name'=>$shop['name']??'','domain'=>$shop['domain']??$shop_domain,'plan'=>$shop['plan_name']??'']);
        break;

    case 'blogs':
        $r = shopify_req($shop_domain, $access_token, 'GET', 'blogs.json');
        if (!$r['ok']) { echo json_encode(['ok'=>false,'error'=>$r['error']]); exit; }
        $blogs = array_map(fn($b)=>['id'=>$b['id'],'title'=>$b['title'],'handle'=>$b['handle']], $r['data']['blogs']??[]);
        echo json_encode(['ok'=>true,'blogs'=>$blogs]);
        break;

    case 'post':
        $title   = trim($input['title']   ?? '');
        $content = trim($input['content'] ?? '');
        $tags    = trim($input['tags']    ?? '');
        $handle  = trim($input['handle']  ?? '');
        $status  = $input['status'] ?? 'draft';
        $blog_id = (int)($input['blog_id'] ?? 0);

        if (!$title || !$content) { echo json_encode(['ok'=>false,'error'=>'Título y contenido requeridos']); exit; }

        // Si no hay blog_id, usar el primero disponible
        if (!$blog_id) {
            $br = shopify_req($shop_domain, $access_token, 'GET', 'blogs.json');
            if (!$br['ok'] || empty($br['data']['blogs'])) {
                echo json_encode(['ok'=>false,'error'=>'No se encontraron blogs en esta tienda Shopify']); exit;
            }
            $blog_id = (int)$br['data']['blogs'][0]['id'];
        }

        $article = [
            'title'     => $title,
            'body_html' => $content,
            'published' => ($status === 'publish'),
        ];
        if ($tags)   $article['tags']   = $tags;
        if ($handle) $article['handle'] = $handle;

        $r = shopify_req($shop_domain, $access_token, 'POST', "blogs/{$blog_id}/articles.json", ['article'=>$article]);
        if (!$r['ok']) { echo json_encode(['ok'=>false,'error'=>'Error publicando en Shopify: '.$r['error']]); exit; }

        $art = $r['data']['article'] ?? [];
        $art_id     = $art['id'] ?? null;
        $art_handle = $art['handle'] ?? '';
        $blog_handle = '';

        // Obtener handle del blog para construir URL
        $blog_r = shopify_req($shop_domain, $access_token, 'GET', "blogs/{$blog_id}.json");
        if ($blog_r['ok']) $blog_handle = $blog_r['data']['blog']['handle'] ?? 'news';

        $pub_domain = $creds['shop_domain'] ?? $shop_domain;
        $pub_domain = str_replace(['https://','http://'], '', $pub_domain);
        $pub_domain = rtrim($pub_domain, '/');
        $view_url   = $art['published_at'] ? "https://{$pub_domain}/blogs/{$blog_handle}/{$art_handle}" : null;
        $edit_url   = "https://{$shop_domain}/admin/articles/{$art_id}";

        echo json_encode([
            'ok'       => true,
            'status'   => $status,
            'article_id'=> $art_id,
            'view_url' => $view_url,
            'edit_url' => $edit_url,
            'blog_id'  => $blog_id,
        ]);
        break;

    default:
        echo json_encode(['ok'=>false,'error'=>'Acción no reconocida']);
}
