<?php
require_once __DIR__.'/../includes/functions.php';
$admin=require_admin(); verify_csrf(); mj_automation_ensure_schema(); $adminTitle='Automation Center';

if($_SERVER['REQUEST_METHOD']==='POST'){
  foreach($_POST['automation']??[] as $key=>$row){
    $key=(string)$key;
    $enabled=!empty($row['is_enabled'])?1:0;
    $notifyUser=!empty($row['notify_user'])?1:0;
    $notifyAdmin=!empty($row['notify_admin'])?1:0;
    $emailUser=!empty($row['email_user'])?1:0;
    $interval=max(1,(int)($row['run_interval_minutes']??1440));
    $repeat=max(1,(int)($row['repeat_limit_per_day']??1));
    $cfg=trim((string)($row['config_json']??'{}'));
    json_decode($cfg,true); if(json_last_error()!==JSON_ERROR_NONE){ $cfg='{}'; }
    q('UPDATE mj_automation_settings SET is_enabled=?,notify_user=?,notify_admin=?,email_user=?,run_interval_minutes=?,repeat_limit_per_day=?,config_json=?,updated_at=NOW() WHERE automation_key=?',
      [$enabled,$notifyUser,$notifyAdmin,$emailUser,$interval,$repeat,$cfg,$key]);
  }
  flash('success','Automation settings saved.');
  redirect('automation-center.php');
}
if(isset($_GET['run'])){
  $res=mj_automation_run_all(true);
  flash('success','Automation runner completed. Actions: '.$res['actions'].' Errors: '.$res['errors']);
  redirect('automation-center.php');
}

$rows=all_rows('SELECT * FROM mj_automation_settings ORDER BY automation_group,automation_key');
$groups=[];
foreach($rows as $r){ $groups[$r['automation_group']][]=$r; }
$stats=[
 'pending_listings'=>safe_count("SELECT COUNT(*) c FROM mj_listings WHERE status='pending'"),
 'pending_companies'=>safe_count("SELECT COUNT(*) c FROM mj_companies WHERE status='pending'"),
 'renewals'=>table_exists('mj_listing_renewal_requests')?safe_count("SELECT COUNT(*) c FROM mj_listing_renewal_requests WHERE status IN ('pending','pending_payment','payment_uploaded')"):0,
 'payments'=>table_exists('mj_upgrade_payment_proofs')?safe_count("SELECT COUNT(*) c FROM mj_upgrade_payment_proofs WHERE status='submitted'"):0,
];
include __DIR__.'/_header.php';
?>
<div class="row">
  <div class="col-lg-3 col-6"><div class="small-box bg-info"><div class="inner"><h3><?=e($stats['pending_listings'])?></h3><p>Pending Listings</p></div><div class="icon"><i class="fas fa-tags"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-primary"><div class="inner"><h3><?=e($stats['pending_companies'])?></h3><p>Pending Companies</p></div><div class="icon"><i class="fas fa-building"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-warning"><div class="inner"><h3><?=e($stats['renewals'])?></h3><p>Upgrade Requests</p></div><div class="icon"><i class="fas fa-star"></i></div></div></div>
  <div class="col-lg-3 col-6"><div class="small-box bg-success"><div class="inner"><h3><?=e($stats['payments'])?></h3><p>Payment Proofs</p></div><div class="icon"><i class="fas fa-receipt"></i></div></div></div>
</div>

<div class="card card-primary card-outline">
  <div class="card-header">
    <h3 class="card-title"><i class="fas fa-robot mr-2"></i>Automation Center</h3>
    <div class="card-tools">
      <a href="automation-center.php?run=1" class="btn btn-sm btn-success" onclick="return confirm('Run all enabled automation now?')"><i class="fas fa-play mr-1"></i>Run Now</a>
      <a href="automation-logs.php" class="btn btn-sm btn-outline-primary">Logs</a>
    </div>
  </div>
  <form method="post">
    <div class="card-body">
      <?php show_flash(); ?>
      <?=csrf_input()?>
      <div class="alert alert-info">
        Every automation is admin-controlled and logged. No payment is auto-approved and no listing/company is auto-approved by default.
        Recommended cron: <code>cron/automation-runner.php</code> every 15 minutes or hourly.
      </div>
      <?php foreach($groups as $g=>$items): ?>
        <h4 class="mt-4 mb-3 text-primary"><?=e(ucwords(str_replace('_',' ',$g)))?></h4>
        <div class="row">
          <?php foreach($items as $r): ?>
            <div class="col-xl-6">
              <div class="card bg-light">
                <div class="card-body">
                  <div class="d-flex justify-content-between">
                    <div><h5 class="font-weight-bold mb-1"><?=e($r['title'])?></h5><p class="text-muted small mb-2"><?=e($r['description'])?></p></div>
                    <div class="custom-control custom-switch">
                      <input type="checkbox" class="custom-control-input" id="en_<?=e($r['automation_key'])?>" name="automation[<?=e($r['automation_key'])?>][is_enabled]" <?=((int)$r['is_enabled']===1?'checked':'')?>>
                      <label class="custom-control-label" for="en_<?=e($r['automation_key'])?>">On</label>
                    </div>
                  </div>
                  <div class="row">
                    <div class="col-md-4"><label class="small">Notify User</label><br><input type="checkbox" name="automation[<?=e($r['automation_key'])?>][notify_user]" <?=((int)$r['notify_user']===1?'checked':'')?>></div>
                    <div class="col-md-4"><label class="small">Notify Admin</label><br><input type="checkbox" name="automation[<?=e($r['automation_key'])?>][notify_admin]" <?=((int)$r['notify_admin']===1?'checked':'')?>></div>
                    <div class="col-md-4"><label class="small">Email User</label><br><input type="checkbox" name="automation[<?=e($r['automation_key'])?>][email_user]" <?=((int)$r['email_user']===1?'checked':'')?>></div>
                    <div class="col-md-6 mt-2"><label class="small">Run interval minutes</label><input class="form-control form-control-sm" type="number" min="1" name="automation[<?=e($r['automation_key'])?>][run_interval_minutes]" value="<?=e($r['run_interval_minutes'])?>"></div>
                    <div class="col-md-6 mt-2"><label class="small">Repeat limit/day</label><input class="form-control form-control-sm" type="number" min="1" name="automation[<?=e($r['automation_key'])?>][repeat_limit_per_day]" value="<?=e($r['repeat_limit_per_day'])?>"></div>
                    <div class="col-12 mt-2"><label class="small">Config JSON</label><textarea class="form-control form-control-sm" rows="2" name="automation[<?=e($r['automation_key'])?>][config_json]"><?=e($r['config_json'])?></textarea></div>
                    <div class="col-12 mt-2"><small class="text-muted">Last run: <?=e($r['last_run_at'] ?: 'Never')?></small></div>
                  </div>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endforeach; ?>
    </div>
    <div class="card-footer"><button class="btn btn-primary btn-lg"><i class="fas fa-save mr-1"></i>Save Automation Settings</button></div>
  </form>
</div>
<?php include __DIR__.'/_footer.php'; ?>
