<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mj_email_helpers.php';
$admin=require_admin(); mj_email_ensure_schema(); verify_csrf();
$adminTitle='SMTP Settings';
$adminSubtitle='Configure multiple SMTP accounts. Email alerts can use failover or random rotation if one SMTP fails.';
if($_SERVER['REQUEST_METHOD']==='POST'){
  $action=(string)($_POST['action']??'');
  try{
    if($action==='save_settings'){
      $settings=['smtp_delivery_mode'=>($_POST['smtp_delivery_mode']??'failover')==='random'?'random':'failover','email_queue_enabled'=>isset($_POST['email_queue_enabled'])?'1':'0','smtp_allow_mail_fallback'=>isset($_POST['smtp_allow_mail_fallback'])?'1':'0','smtp_timeout_seconds'=>(string)max(5,min(60,(int)($_POST['smtp_timeout_seconds']??15))),'smtp_default_from_email'=>trim((string)($_POST['smtp_default_from_email']??'')),'smtp_default_from_name'=>trim((string)($_POST['smtp_default_from_name']??'')),'admin_email'=>trim((string)($_POST['admin_email']??''))];
      foreach($settings as $k=>$v){ q('INSERT INTO mj_settings(setting_key,setting_value) VALUES(?,?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value), updated_at=NOW()',[$k,$v]); }
      flash('success','SMTP global settings saved.');
    } elseif($action==='save_account'){
      $id=(int)($_POST['id']??0); $name=trim((string)($_POST['account_name']??'')); $host=trim((string)($_POST['host']??'')); $from=trim((string)($_POST['from_email']??''));
      if($name===''||$host===''||!filter_var($from,FILTER_VALIDATE_EMAIL)) throw new RuntimeException('Account name, host and valid from email are required.');
      $enc=in_array($_POST['encryption']??'tls',['tls','ssl','none'],true)?(string)$_POST['encryption']:'tls'; $port=max(1,min(65535,(int)($_POST['port']??587)));
      $pass=(string)($_POST['password']??'');
      if($id>0){
        $existing=one('SELECT * FROM mj_smtp_accounts WHERE id=? LIMIT 1',[$id]); if(!$existing) throw new RuntimeException('SMTP account not found.');
        if($pass==='') $pass=(string)($existing['password']??'');
        q('UPDATE mj_smtp_accounts SET account_name=?,host=?,port=?,encryption=?,username=?,password=?,from_email=?,from_name=?,reply_to_email=?,is_active=?,priority_order=?,daily_limit=?,updated_at=NOW() WHERE id=?',[$name,$host,$port,$enc,trim((string)($_POST['username']??'')),$pass,$from,trim((string)($_POST['from_name']??'')),trim((string)($_POST['reply_to_email']??'')),isset($_POST['is_active'])?1:0,(int)($_POST['priority_order']??100),(int)($_POST['daily_limit']??0),$id]);
        flash('success','SMTP account updated.');
      } else {
        q('INSERT INTO mj_smtp_accounts(account_name,host,port,encryption,username,password,from_email,from_name,reply_to_email,is_active,priority_order,daily_limit,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())',[$name,$host,$port,$enc,trim((string)($_POST['username']??'')),$pass,$from,trim((string)($_POST['from_name']??'')),trim((string)($_POST['reply_to_email']??'')),isset($_POST['is_active'])?1:0,(int)($_POST['priority_order']??100),(int)($_POST['daily_limit']??0)]);
        flash('success','SMTP account added.');
      }
    } elseif($action==='toggle'){
      $id=(int)($_POST['id']??0); q('UPDATE mj_smtp_accounts SET is_active=IF(is_active=1,0,1), updated_at=NOW() WHERE id=?',[$id]); flash('success','SMTP status changed.');
    } elseif($action==='delete'){
      $id=(int)($_POST['id']??0); q('DELETE FROM mj_smtp_accounts WHERE id=?',[$id]); flash('success','SMTP account deleted.');
    } elseif($action==='test'){
      $email=trim((string)($_POST['test_email']??'')); if(!filter_var($email,FILTER_VALIDATE_EMAIL)) throw new RuntimeException('Enter valid test email.');
      $res=mj_send_email($email,'MJ Marketplace SMTP Test','<h2>SMTP test successful</h2><p>This test email was sent from MJ Marketplace using your SMTP settings.</p>','SMTP test successful',['force_send'=>true,'template_key'=>'smtp_test']);
      if(!empty($res['success'])) flash('success','Test email sent using '.e((string)($res['method']??'smtp')).'.'); else throw new RuntimeException($res['error']??'Test email failed.');
    } elseif($action==='process_queue'){
      $r=mj_process_email_queue(50); flash('success','Queue processed. Sent: '.$r['sent'].' Failed: '.$r['failed']);
    }
  }catch(Throwable $e){ flash('error',$e->getMessage()); }
  redirect('smtp-settings.php');
}
$editId=(int)($_GET['edit']??0); $edit=$editId?one('SELECT * FROM mj_smtp_accounts WHERE id=? LIMIT 1',[$editId]):null;
$accounts=table_exists('mj_smtp_accounts')?all_rows('SELECT * FROM mj_smtp_accounts ORDER BY priority_order,id'):[];
$logs=table_exists('mj_email_send_log')?all_rows('SELECT * FROM mj_email_send_log ORDER BY id DESC LIMIT 20'):[];
$pending=table_exists('mj_email_queue')?safe_count('SELECT COUNT(*) c FROM mj_email_queue WHERE status IN ("pending","retry")'):0;
include __DIR__.'/_header.php';
?>
<div class="alert alert-info"><i class="fas fa-envelope mr-1"></i><b>Multiple SMTP supported:</b> Failover tries SMTP accounts by priority. Random mode rotates active SMTP accounts. If one fails, the system tries the next active account.</div>
<div class="row">
 <div class="col-lg-8">
  <div class="card card-primary card-outline"><div class="card-header"><h3 class="card-title"><i class="fas fa-server mr-2"></i>SMTP Accounts</h3><div class="card-tools"><span class="badge badge-info"><?=count($accounts)?> accounts</span></div></div><div class="card-body table-responsive">
   <table class="table table-striped table-hover"><thead><tr><th>Priority</th><th>Account</th><th>Host</th><th>From</th><th>Status</th><th>Sent Today</th><th>Last Error</th><th>Action</th></tr></thead><tbody><?php if(!$accounts): ?><tr><td colspan="8" class="text-center text-muted py-4">No SMTP accounts yet. Add at least one SMTP account to receive email alerts.</td></tr><?php endif; ?><?php foreach($accounts as $a): ?><tr><td><?=e($a['priority_order'])?></td><td><b><?=e($a['account_name'])?></b><br><small><?=e($a['username']?:'No username')?></small></td><td><?=e($a['host'].':'.$a['port'].' '.$a['encryption'])?></td><td><?=e($a['from_name'])?><br><small><?=e($a['from_email'])?></small></td><td><span class="badge badge-<?=!empty($a['is_active'])?'success':'secondary'?>"><?=!empty($a['is_active'])?'Active':'Disabled'?></span></td><td><?=e($a['sent_today'])?><?=((int)$a['daily_limit']>0?' / '.e($a['daily_limit']):'')?></td><td><small class="text-danger"><?=e(mb_strimwidth((string)($a['last_error']??''),0,80,'...'))?></small></td><td><a class="btn btn-xs btn-outline-primary" href="smtp-settings.php?edit=<?=(int)$a['id']?>">Edit</a><form method="post" class="d-inline"><?=csrf_input()?><input type="hidden" name="id" value="<?=(int)$a['id']?>"><button class="btn btn-xs btn-outline-warning" name="action" value="toggle">Toggle</button><button class="btn btn-xs btn-outline-danger" name="action" value="delete" onclick="return confirm('Delete this SMTP account?')">Delete</button></form></td></tr><?php endforeach; ?></tbody></table>
  </div></div>
  <div class="card"><div class="card-header"><h3 class="card-title">Recent Email Logs</h3><div class="card-tools"><span class="badge badge-warning"><?=$pending?> pending queue</span></div></div><div class="card-body table-responsive"><table class="table table-sm"><thead><tr><th>Date</th><th>To</th><th>Subject</th><th>Status</th><th>Error</th></tr></thead><tbody><?php foreach($logs as $l): ?><tr><td><small><?=e($l['created_at'])?></small></td><td><?=e($l['to_email'])?></td><td><?=e(mb_strimwidth($l['subject'],0,50,'...'))?></td><td><span class="badge badge-<?=$l['status']==='sent'?'success':'danger'?>"><?=e($l['status'])?></span></td><td><small><?=e(mb_strimwidth((string)$l['error_message'],0,90,'...'))?></small></td></tr><?php endforeach; ?><?php if(!$logs): ?><tr><td colspan="5" class="text-muted text-center">No email log yet.</td></tr><?php endif; ?></tbody></table><form method="post" class="mt-2"><?=csrf_input()?><button name="action" value="process_queue" class="btn btn-outline-primary btn-sm"><i class="fas fa-play mr-1"></i>Process Email Queue Now</button></form></div></div>
 </div>
 <div class="col-lg-4">
  <div class="card card-success card-outline"><div class="card-header"><h3 class="card-title"><?= $edit?'Edit SMTP':'Add SMTP' ?></h3></div><form method="post"><?=csrf_input()?><input type="hidden" name="id" value="<?=e($edit['id']??0)?>"><div class="card-body">
   <input type="hidden" name="action" value="save_account"><div class="form-group"><label>Account Name *</label><input class="form-control" name="account_name" required value="<?=e($edit['account_name']??'')?>"></div><div class="form-group"><label>Host *</label><input class="form-control" name="host" required placeholder="smtp.example.com" value="<?=e($edit['host']??'')?>"></div><div class="form-row"><div class="form-group col-6"><label>Port</label><input class="form-control" name="port" type="number" value="<?=e($edit['port']??587)?>"></div><div class="form-group col-6"><label>Encryption</label><select class="form-control" name="encryption"><?php foreach(['tls'=>'TLS/STARTTLS','ssl'=>'SSL','none'=>'None'] as $k=>$v): ?><option value="<?=e($k)?>" <?=(($edit['encryption']??'tls')===$k?'selected':'')?>><?=e($v)?></option><?php endforeach; ?></select></div></div><div class="form-group"><label>Username</label><input class="form-control" name="username" value="<?=e($edit['username']??'')?>"></div><div class="form-group"><label>Password <?= $edit?'(leave blank to keep)':'' ?></label><input class="form-control" type="password" name="password" autocomplete="new-password"></div><div class="form-group"><label>From Email *</label><input class="form-control" type="email" required name="from_email" value="<?=e($edit['from_email']??setting('smtp_default_from_email',''))?>"></div><div class="form-group"><label>From Name</label><input class="form-control" name="from_name" value="<?=e($edit['from_name']??setting('smtp_default_from_name',setting('site_name','MJ Marketplace')))?>"></div><div class="form-group"><label>Reply-To Email</label><input class="form-control" type="email" name="reply_to_email" value="<?=e($edit['reply_to_email']??'')?>"></div><div class="form-row"><div class="form-group col-6"><label>Priority</label><input class="form-control" name="priority_order" type="number" value="<?=e($edit['priority_order']??100)?>"></div><div class="form-group col-6"><label>Daily Limit</label><input class="form-control" name="daily_limit" type="number" value="<?=e($edit['daily_limit']??0)?>"></div></div><div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" id="active" name="is_active" <?=(!isset($edit['is_active'])||$edit['is_active'])?'checked':''?>><label class="custom-control-label" for="active">Active</label></div>
  </div><div class="card-footer"><button class="btn btn-success btn-block"><i class="fas fa-save mr-1"></i>Save SMTP</button><?php if($edit): ?><a class="btn btn-light btn-block" href="smtp-settings.php">Cancel Edit</a><?php endif; ?></div></form></div>
  <div class="card card-primary card-outline"><div class="card-header"><h3 class="card-title">Global Email Settings</h3></div><form method="post"><?=csrf_input()?><input type="hidden" name="action" value="save_settings"><div class="card-body"><div class="form-group"><label>Delivery Mode</label><select class="form-control" name="smtp_delivery_mode"><option value="failover" <?=setting('smtp_delivery_mode','failover')==='failover'?'selected':''?>>Failover by Priority</option><option value="random" <?=setting('smtp_delivery_mode','failover')==='random'?'selected':''?>>Random Active SMTP</option></select></div><div class="form-group"><label>Admin Email</label><input class="form-control" type="email" name="admin_email" value="<?=e(setting('admin_email',''))?>"></div><div class="form-group"><label>Default From Email</label><input class="form-control" type="email" name="smtp_default_from_email" value="<?=e(setting('smtp_default_from_email',''))?>"></div><div class="form-group"><label>Default From Name</label><input class="form-control" name="smtp_default_from_name" value="<?=e(setting('smtp_default_from_name',setting('site_name','MJ Marketplace')))?>"></div><div class="form-group"><label>Timeout Seconds</label><input class="form-control" type="number" name="smtp_timeout_seconds" value="<?=e(setting('smtp_timeout_seconds','15'))?>"></div><div class="custom-control custom-switch mb-2"><input class="custom-control-input" type="checkbox" id="queue" name="email_queue_enabled" <?=setting('email_queue_enabled','1')==='1'?'checked':''?>><label class="custom-control-label" for="queue">Queue automatic emails</label></div><div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" id="fallback" name="smtp_allow_mail_fallback" <?=setting('smtp_allow_mail_fallback','1')==='1'?'checked':''?>><label class="custom-control-label" for="fallback">Allow PHP mail fallback</label></div></div><div class="card-footer"><button class="btn btn-primary btn-block">Save Settings</button></div></form></div>
  <div class="card"><div class="card-header"><h3 class="card-title">Send Test Email</h3></div><form method="post"><?=csrf_input()?><div class="card-body"><input type="hidden" name="action" value="test"><input class="form-control" type="email" required name="test_email" placeholder="you@example.com"></div><div class="card-footer"><button class="btn btn-outline-primary btn-block"><i class="fas fa-paper-plane mr-1"></i>Send Test</button></div></form></div>
 </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
