<?php
require_once __DIR__.'/../includes/functions.php';
$admin=require_admin(); verify_csrf(); mj_company_module_ensure_schema(); mj_review_ensure_schema();
$adminTitle='Company Update Reviews'; $adminSubtitle='Review user-submitted company profile changes before they replace the live public version.';
if($_SERVER['REQUEST_METHOD']==='POST'){
    $rid=(int)($_POST['revision_id']??0); $action=(string)($_POST['action']??'');
    try{
        $rev=one('SELECT * FROM mj_company_revisions WHERE id=? LIMIT 1',[$rid]);
        if(!$rev) throw new RuntimeException('Revision not found.');
        if($rev['status']!=='pending') throw new RuntimeException('This revision was already reviewed.');
        if($action==='approve'){
            mj_review_apply_company($rev,(int)$admin['id'],trim((string)($_POST['admin_note']??'')));
            flash('success','Company update approved and live profile updated.');
        } elseif($action==='reject'){
            $reason=trim((string)($_POST['reject_reason']??'')); if($reason==='') $reason='Please review and update the submitted company information.';
            q('UPDATE mj_company_revisions SET status="rejected", admin_id=?, reject_reason=?, admin_note=?, reviewed_at=NOW() WHERE id=?',[(int)$admin['id'],$reason,trim((string)($_POST['admin_note']??'')),$rid]);
            $co=one('SELECT id,name,status FROM mj_companies WHERE id=? LIMIT 1',[(int)$rev['company_id']]);
            if($co && function_exists('mj_company_timeline_add')) mj_company_timeline_add((int)$co['id'],'admin',(int)$admin['id'],'revision_rejected','Company update rejected. '.$reason,(string)$co['status'],(string)$co['status']);
            if(!empty($rev['user_id'])) mj263_notify((int)$rev['user_id'],null,'company_revision_rejected','Company update rejected','Reason: '.$reason,'my-companies.php','high',true);
            admin_log('company_revision_rejected','mj_company_revisions',$rid,['company_id'=>(int)$rev['company_id'],'reason'=>$reason]);
            flash('success','Company update rejected.');
        }
    }catch(Throwable $e){ flash('error',$e->getMessage()); }
    redirect('company-revisions.php');
}
$status=$_GET['status']??'pending';
$rows=[];
try{
    $rows=all_rows('SELECT r.*,co.name company_name,u.name user_name,u.email user_email FROM mj_company_revisions r LEFT JOIN mj_companies co ON co.id=r.company_id LEFT JOIN mj_users u ON u.id=r.user_id WHERE r.status=? ORDER BY r.id DESC LIMIT 200',[$status]);
}catch(Throwable $e){}
include __DIR__.'/_header.php';
$fields=['name'=>'Company name','registration_no'=>'Registration no.','description'=>'Description','country_id'=>'Country','state_id'=>'State','city_id'=>'City','category_id'=>'Category','phone'=>'Phone','whatsapp'=>'WhatsApp','email'=>'Email','website'=>'Website','address'=>'Address','logo'=>'Logo','cover_image'=>'Cover image'];
?>
<div class="card card-warning card-outline">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-building mr-2"></i>Company Update Reviews</h3><div class="card-tools"><a class="btn btn-sm btn-secondary" href="companies.php">Companies</a> <a class="btn btn-sm btn-info" href="action-queue.php">Action Queue</a></div></div>
  <div class="card-body">
    <div class="alert alert-info"><b>Safe workflow:</b> the old company page remains live until you approve the user update. Rejecting keeps the current company unchanged.</div>
    <form class="mb-3"><select name="status" class="form-control" style="max-width:240px" onchange="this.form.submit()"><?php foreach(['pending','approved','rejected','cancelled'] as $s): ?><option value="<?=e($s)?>" <?=$status===$s?'selected':''?>><?=e(ucfirst($s))?></option><?php endforeach; ?></select></form>
    <?php if(!$rows): ?><div class="alert alert-light border text-center py-4">No company update reviews found.</div><?php endif; ?>
    <?php foreach($rows as $r): $old=json_decode((string)$r['old_data_json'],true)?:[]; $new=json_decode((string)$r['new_data_json'],true)?:[]; $extra=json_decode((string)$r['new_extra_json'],true)?:[]; ?>
      <div class="card mb-3 shadow-sm">
        <div class="card-header bg-light"><b>#<?=e($r['company_id'])?> <?=e($r['company_name'] ?: ($old['name'] ?? 'Company'))?></b><span class="badge badge-warning ml-2"><?=e($r['status'])?></span><small class="float-right text-muted">Submitted by <?=e($r['user_name'] ?: 'User')?> • <?=e($r['submitted_at'])?></small></div>
        <div class="card-body">
          <div class="row">
            <div class="col-lg-6"><h6 class="font-weight-bold">Current Live Version</h6><table class="table table-sm table-bordered"><tbody><?php foreach($fields as $k=>$label): ?><tr><th style="width:135px"><?=e($label)?></th><td><?=e(mj_review_short($old[$k] ?? '', 220))?></td></tr><?php endforeach; ?></tbody></table></div>
            <div class="col-lg-6"><h6 class="font-weight-bold">Requested New Version</h6><table class="table table-sm table-bordered"><tbody><?php foreach($fields as $k=>$label): $changed=(string)($old[$k]??'') !== (string)($new[$k]??''); ?><tr class="<?=$changed?'table-warning':''?>"><th style="width:135px"><?=e($label)?></th><td><?=e(mj_review_short($new[$k] ?? '', 220))?></td></tr><?php endforeach; ?></tbody></table><?php if(isset($extra['services_text'])): ?><div class="alert alert-light border"><b>Services update:</b><br><?=nl2br(e(mj_review_short($extra['services_text'],500)))?></div><?php endif; ?></div>
          </div>
          <?php if($status==='pending'): ?><form method="post" class="border-top pt-3 mt-2"><?=csrf_input()?><input type="hidden" name="revision_id" value="<?=e($r['id'])?>"><div class="form-row"><div class="col-md-4 mb-2"><input class="form-control" name="admin_note" placeholder="Admin note"></div><div class="col-md-4 mb-2"><input class="form-control" name="reject_reason" placeholder="Reject reason"></div><div class="col-md-4 mb-2"><button class="btn btn-success" name="action" value="approve" onclick="return confirm('Approve this company update?')"><i class="fas fa-check mr-1"></i>Approve Update</button> <button class="btn btn-danger" name="action" value="reject" onclick="return confirm('Reject this company update?')"><i class="fas fa-times mr-1"></i>Reject</button></div></div></form><?php endif; ?>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
