<?php
require_once __DIR__.'/../includes/functions.php';
$admin=require_admin(); mj_automation_ensure_schema(); $adminTitle='Automation Logs';
$key=trim((string)($_GET['key']??'')); $status=trim((string)($_GET['status']??'')); $where=[]; $params=[];
if($key!==''){ $where[]='automation_key=?'; $params[]=$key; }
if($status!==''){ $where[]='status=?'; $params[]=$status; }
$rows=all_rows('SELECT * FROM mj_automation_logs '.($where?'WHERE '.implode(' AND ',$where):'').' ORDER BY id DESC LIMIT 1000',$params);
$keys=all_rows('SELECT automation_key,title FROM mj_automation_settings ORDER BY automation_group,automation_key');
include __DIR__.'/_header.php'; ?>
<div class="card card-primary card-outline">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-list mr-2"></i>Automation Logs</h3><div class="card-tools"><a href="automation-center.php" class="btn btn-sm btn-outline-primary">Automation Center</a></div></div>
  <div class="card-body"><?php show_flash(); ?>
    <form class="form-inline mb-3">
      <select class="form-control mr-2" name="key"><option value="">All automation</option><?php foreach($keys as $k): ?><option value="<?=e($k['automation_key'])?>" <?=$key===$k['automation_key']?'selected':''?>><?=e($k['title'])?></option><?php endforeach; ?></select>
      <select class="form-control mr-2" name="status"><option value="">All status</option><option value="success" <?=$status==='success'?'selected':''?>>Success</option><option value="error" <?=$status==='error'?'selected':''?>>Error</option></select>
      <button class="btn btn-primary">Filter</button>
    </form>
    <div class="table-responsive"><table class="table table-hover">
      <thead><tr><th>Date</th><th>Automation</th><th>Target</th><th>Action</th><th>Message</th><th>Status</th></tr></thead>
      <tbody><?php foreach($rows as $r): ?><tr>
        <td><?=e($r['created_at'])?></td><td><b><?=e($r['automation_key'])?></b><br><small><?=e($r['automation_group'])?></small></td>
        <td><?=e($r['target_type'])?> #<?=e($r['target_id'])?></td><td><?=e($r['action_taken'])?></td><td><?=e($r['message'])?><?php if($r['error_message']): ?><br><small class="text-danger"><?=e($r['error_message'])?></small><?php endif; ?></td>
        <td><span class="badge badge-<?=e($r['status']==='error'?'danger':'success')?>"><?=e($r['status'])?></span></td>
      </tr><?php endforeach; ?><?php if(!$rows): ?><tr><td colspan="6" class="text-center text-muted py-4">No automation logs found.</td></tr><?php endif; ?></tbody>
    </table></div>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
