<?php
use Plugin\ItemShop\ItemShop;

function itemshopCampaignEsc($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function itemshopCampaignDate($shop,$value) {
    $local=$shop->localDateValue($value);
    return $local!=='' ? str_replace('T',' ',$local) : '—';
}
function itemshopCampaignStatus($status) {
    $map=array('scheduled'=>array('info','Programada'),'active'=>array('success','Activa'),'completed'=>array('default','Finalizada'),'cancelled'=>array('warning','Cancelada'));
    $cfg=$map[$status]??array('danger',strtoupper((string)$status));
    return '<span class="label label-'.$cfg[0].'">'.htmlspecialchars($cfg[1],ENT_QUOTES,'UTF-8').'</span>';
}

$shop=new ItemShop();
if(!$shop->schemaReady()) { message('warning','Primero instala las tablas desde Arsenal Nexora → Configuración.'); return; }
if(!$shop->campaignSchemaReady()) { message('warning','Campañas requieren Arsenal 1.7.0. Ve a Configuración y pulsa Instalar / validar tablas en este reino.'); return; }

if(($_SERVER['REQUEST_METHOD']??'GET')==='POST') {
    try {
        if(isset($_POST['save_campaign'])) {
            $id=$shop->saveCampaign($_POST);
            message('success','Campaña #'.$id.' guardada. El cron del reino la ejecutará según su horario.');
            $_GET['id']=$id;
        } elseif(isset($_POST['cancel_campaign'])) {
            $shop->cancelCampaign((int)($_POST['campaign_id']??0));
            message('success','Campaña programada cancelada. No se modificó el catálogo.');
        } elseif(isset($_POST['start_campaign_now'])) {
            $result=$shop->startCampaign((int)($_POST['campaign_id']??0),true);
            message('success',number_format((int)($result['affected']??0)).' configuración'.((int)($result['affected']??0)===1?'':'es').' modificada'.((int)($result['affected']??0)===1?'':'s').' al iniciar la campaña.');
        } elseif(isset($_POST['end_campaign_now'])) {
            $result=$shop->endCampaign((int)($_POST['campaign_id']??0),true);
            $text='Campaña finalizada. '.number_format((int)($result['restored']??0)).' configuración'.((int)($result['restored']??0)===1?'':'es').' restaurada'.((int)($result['restored']??0)===1?'':'s').'.';
            if((int)($result['conflicts']??0)>0) $text.=' '.number_format((int)$result['conflicts']).' conflicto'.((int)$result['conflicts']===1?'':'s').' quedó'.((int)$result['conflicts']===1?'':'aron').' sin sobrescribir.';
            message((int)($result['conflicts']??0)>0?'warning':'success',$text);
        } elseif(isset($_POST['process_campaigns'])) {
            $result=$shop->processCampaigns(50);
            $text='Procesamiento manual: '.number_format((int)$result['started']).' iniciada(s), '.number_format((int)$result['ended']).' finalizada(s).';
            if(!empty($result['errors'])) $text.=' Errores: '.implode(' | ',array_slice($result['errors'],0,3));
            message(!empty($result['errors'])?'warning':'success',itemshopCampaignEsc($text));
        } elseif(isset($_POST['ensure_campaign_cron'])) {
            $shop->ensureCampaignCron();
            message('success','Cron Arsenal Campaign Manager registrado y habilitado cada 60 segundos.');
        }
    } catch(Throwable $e) { message('error',itemshopCampaignEsc($e->getMessage())); }
}

$collections=$shop->getCollections();
$campaigns=$shop->getCampaigns(120);
$editId=isset($_GET['id']) && filter_var($_GET['id'],FILTER_VALIDATE_INT)!==false ? (int)$_GET['id'] : 0;
$editing=$editId>0 ? $shop->getCampaign($editId) : null;
if($editing && (string)$editing['status']!=='scheduled') $editing=null;
$now=new DateTimeImmutable('now',new DateTimeZone(date_default_timezone_get()));
$defaultStart=$now->modify('+5 minutes')->format('Y-m-d\TH:i');
$defaultEnd=$now->modify('+3 days')->format('Y-m-d\TH:i');
$cronReady=$shop->campaignCronReady();
?>
<link rel="stylesheet" href="<?php echo itemshopCampaignEsc(__PATH_ADMINCP_HOME__); ?>css/itemshop-admin.css?v=170">
<div id="itemshop-admin-campaigns">
    <h1 class="page-header">Campañas · <?php echo itemshopCampaignEsc($shop->getRealmLabel()); ?></h1>
    <div class="itemshop-admin-toolbar">
        <a href="index.php?module=itemshop&amp;page=items">← Catálogo</a>
        <a href="index.php?module=itemshop&amp;page=collections">Colecciones</a>
        <a href="index.php?module=itemshop&amp;page=operations">Operaciones</a>
        <a href="index.php?module=itemshop&amp;page=settings">Configuración</a>
    </div>

    <div class="itemshop-campaign-health <?php echo $cronReady?'is-ready':'is-warning'; ?>">
        <div><span>Automatización</span><strong><?php echo $cronReady?'CRON ACTIVO · 60 S':'CRON REQUIERE ATENCIÓN'; ?></strong><small>Inicio y cierre se procesan por reino usando el cron local realm-aware.</small></div>
        <div>
            <form method="post" style="display:inline"><button class="btn btn-default btn-sm" name="process_campaigns" value="1">Procesar ahora</button></form>
            <?php if(!$cronReady) { ?><form method="post" style="display:inline"><button class="btn btn-primary btn-sm" name="ensure_campaign_cron" value="1">Registrar / habilitar cron</button></form><?php } ?>
        </div>
    </div>

    <div class="alert alert-info"><strong>Restauración segura.</strong> Al iniciar, Arsenal guarda solamente los campos que la campaña cambia. Al finalizar compara el estado actual contra el estado aplicado; si alguien editó una configuración durante la campaña, no la sobrescribe y registra un conflicto.</div>

    <div class="row">
        <div class="col-lg-5">
            <form method="post">
                <input type="hidden" name="campaign_id" value="<?php echo $editing?(int)$editing['id']:0; ?>">
                <div class="panel panel-default itemshop-admin-panel">
                    <div class="panel-heading"><strong><?php echo $editing?'Editar campaña programada':'Nueva campaña'; ?></strong><span><?php echo itemshopCampaignEsc($shop->getRealmLabel()); ?></span></div>
                    <div class="panel-body">
                        <?php if(!$collections) { ?><div class="alert alert-warning">Primero crea una <a href="index.php?module=itemshop&amp;page=collections">colección</a> con al menos un producto.</div><?php } ?>
                        <div class="form-group"><label>Nombre</label><input class="form-control" name="name" maxlength="120" required value="<?php echo itemshopCampaignEsc($editing['name']??''); ?>" placeholder="Ej. Weekend Socket"></div>
                        <div class="form-group"><label>Colección</label><select class="form-control" name="collection_id" required><option value="">Seleccionar…</option><?php foreach($collections as $collection) { ?><option value="<?php echo (int)$collection['id']; ?>"<?php echo $editing && (int)$editing['collection_id']===(int)$collection['id']?' selected':''; ?>><?php echo itemshopCampaignEsc($collection['name']); ?> · <?php echo number_format((int)$collection['item_count']); ?> ítems</option><?php } ?></select></div>
                        <div class="row"><div class="col-sm-6"><div class="form-group"><label>Inicio</label><input class="form-control" type="datetime-local" name="start_at" required value="<?php echo itemshopCampaignEsc($editing?$shop->localDateValue($editing['start_at']):$defaultStart); ?>"></div></div><div class="col-sm-6"><div class="form-group"><label>Fin</label><input class="form-control" type="datetime-local" name="end_at" required value="<?php echo itemshopCampaignEsc($editing?$shop->localDateValue($editing['end_at']):$defaultEnd); ?>"></div></div></div>
                        <div class="itemshop-campaign-actions-config">
                            <label><input type="checkbox" name="publish_on_start" value="1"<?php echo $editing && !empty($editing['publish_on_start'])?' checked':''; ?>> Publicar colección al iniciar</label>
                            <label><input type="checkbox" name="feature_on_start" value="1"<?php echo $editing && !empty($editing['feature_on_start'])?' checked':''; ?>> Marcar como destacados</label>
                            <div class="form-group"><label>Descuento promocional (%)</label><input class="form-control" type="number" min="1" max="95" name="discount_percent" value="<?php echo itemshopCampaignEsc($editing && $editing['discount_percent']!==null?$editing['discount_percent']:''); ?>" placeholder="Ej. 20 · vacío = sin descuento"><small>Se calcula sobre el precio normal de cada configuración y la promoción queda limitada al horario de campaña.</small></div>
                            <input type="hidden" name="restore_on_end" value="0"><label><input type="checkbox" name="restore_on_end" value="1"<?php echo !$editing || !empty($editing['restore_on_end'])?' checked':''; ?>> Restaurar estado anterior al finalizar</label>
                        </div>
                        <button class="btn btn-primary" type="submit" name="save_campaign" value="1"<?php echo !$collections?' disabled':''; ?>><?php echo $editing?'Guardar cambios':'Programar campaña'; ?></button>
                        <?php if($editing) { ?><a class="btn btn-default" href="index.php?module=itemshop&amp;page=campaigns">Cancelar edición</a><?php } ?>
                    </div>
                </div>
            </form>
        </div>
        <div class="col-lg-7">
            <div class="panel panel-default itemshop-admin-panel">
                <div class="panel-heading"><strong>Calendario operativo</strong><span><?php echo number_format(count($campaigns)); ?> campañas recientes</span></div>
                <div class="panel-body">
                    <?php if(!$campaigns) { ?><p class="text-muted">Todavía no hay campañas.</p><?php } else { ?>
                    <div class="table-responsive"><table class="table table-striped table-bordered itemshop-campaign-table"><thead><tr><th>Campaña</th><th>Horario</th><th>Acciones</th><th>Estado</th><th></th></tr></thead><tbody>
                    <?php foreach($campaigns as $campaign) {
                        $status=(string)$campaign['status']; $actions=array();
                        if(!empty($campaign['publish_on_start'])) $actions[]='Publicar';
                        if(!empty($campaign['feature_on_start'])) $actions[]='Destacar';
                        if($campaign['discount_percent']!==null && $campaign['discount_percent']!=='') $actions[]='-'.(int)$campaign['discount_percent'].'%';
                    ?>
                        <tr>
                            <td><strong>#<?php echo (int)$campaign['id']; ?> · <?php echo itemshopCampaignEsc($campaign['name']); ?></strong><br><small><?php echo itemshopCampaignEsc($campaign['collection_name']); ?> · <?php echo number_format((int)$campaign['affected']); ?> modificados<?php if((int)$campaign['conflict_count']>0) echo ' · '.number_format((int)$campaign['conflict_count']).' conflictos'; ?></small><?php if(!empty($campaign['last_error'])) { ?><div class="text-danger"><small><?php echo itemshopCampaignEsc($campaign['last_error']); ?></small></div><?php } ?></td>
                            <td><small><?php echo itemshopCampaignEsc(itemshopCampaignDate($shop,$campaign['start_at'])); ?><br>→ <?php echo itemshopCampaignEsc(itemshopCampaignDate($shop,$campaign['end_at'])); ?></small></td>
                            <td><?php echo itemshopCampaignEsc(implode(' · ',$actions)); ?><?php if(!empty($campaign['restore_on_end'])) { ?><br><small>Restaurar al cierre</small><?php } ?></td>
                            <td><?php echo itemshopCampaignStatus($status); ?></td>
                            <td style="white-space:nowrap">
                                <?php if($status==='scheduled') { ?>
                                    <a class="btn btn-default btn-xs" href="index.php?module=itemshop&amp;page=campaigns&amp;id=<?php echo (int)$campaign['id']; ?>">Editar</a>
                                    <form method="post" style="display:inline" onsubmit="return confirm('¿Iniciar esta campaña ahora? Si estaba programada para más tarde, su inicio se adelantará al momento actual.');"><input type="hidden" name="campaign_id" value="<?php echo (int)$campaign['id']; ?>"><button class="btn btn-success btn-xs" name="start_campaign_now" value="1">Iniciar ahora</button></form>
                                    <form method="post" style="display:inline" onsubmit="return confirm('¿Cancelar esta campaña programada? No se tocará el catálogo.');"><input type="hidden" name="campaign_id" value="<?php echo (int)$campaign['id']; ?>"><button class="btn btn-warning btn-xs" name="cancel_campaign" value="1">Cancelar</button></form>
                                <?php } elseif($status==='active') { ?>
                                    <form method="post" style="display:inline" onsubmit="return confirm('¿Finalizar esta campaña ahora? Arsenal intentará restaurar el estado anterior y protegerá cualquier edición posterior como conflicto.');"><input type="hidden" name="campaign_id" value="<?php echo (int)$campaign['id']; ?>"><button class="btn btn-warning btn-xs" name="end_campaign_now" value="1">Finalizar ahora</button></form>
                                <?php } else { ?><span class="text-muted">Histórico</span><?php } ?>
                            </td>
                        </tr>
                    <?php } ?>
                    </tbody></table></div>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
</div>
