<?php
require_once __DIR__.'/includes/functions.php';
mj263_schema();
mj_trust_bundle_ensure_schema();
verify_csrf();

$type = strtolower(trim((string)($_GET['type'] ?? $_POST['type'] ?? 'listing')));
$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
$isCompany = $type === 'company';
$pageTitle = $isCompany ? 'Report Company' : 'Report Listing';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $reason = trim((string)($_POST['reason'] ?? ''));
        if ($reason === '') { throw new Exception('Please choose a reason.'); }
        $msg = trim((string)($_POST['message'] ?? ''));
        if ($id <= 0) { throw new Exception('Invalid report.'); }

        if ($isCompany) {
            if (!table_exists('mj_reports')) {
                q("CREATE TABLE IF NOT EXISTS mj_reports (
                    id BIGINT AUTO_INCREMENT PRIMARY KEY,
                    reporter_id BIGINT NULL,
                    target_type VARCHAR(60) NOT NULL,
                    target_id BIGINT NOT NULL,
                    reason VARCHAR(160) NOT NULL,
                    details TEXT NULL,
                    status VARCHAR(40) DEFAULT 'new',
                    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    KEY idx_target(target_type,target_id),
                    KEY idx_status(status)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
            }
            q('INSERT INTO mj_reports(reporter_id,target_type,target_id,reason,details,status,created_at) VALUES(?,?,?,?,?,"new",NOW())',
              [$_SESSION['user_id'] ?? null, 'company', $id, $reason, $msg]);
            try {
                mj_create_admin_alert([
                    'alert_key'=>'company_report_'.$id.'_'.date('YmdHi'),
                    'alert_type'=>'company_report',
                    'module_name'=>'companies',
                    'priority'=>'high',
                    'title'=>'Company reported',
                    'message'=>'Reason: '.$reason,
                    'action_url'=>'companies.php',
                    'action_label'=>'Review',
                    'related_type'=>'company',
                    'related_id'=>$id
                ]);
            } catch (Throwable $e) {}
            flash('success','Thank you. Our team will review this company.');
            redirect('company.php?id='.$id);
        }

        if (table_exists('mj_listing_reports')) {
            q('INSERT INTO mj_listing_reports(listing_id,user_id,reason,message,created_at) VALUES(?,?,?,?,NOW())',
              [$id, $_SESSION['user_id'] ?? null, $reason, $msg]);
            try {
                mj_create_admin_alert([
                    'alert_key'=>'listing_report_'.$id.'_'.date('YmdHi'),
                    'alert_type'=>'listing_report',
                    'module_name'=>'listings',
                    'priority'=>'high',
                    'title'=>'Listing reported',
                    'message'=>'Reason: '.$reason,
                    'action_url'=>'reported-listings.php',
                    'action_label'=>'Review',
                    'related_type'=>'listing',
                    'related_id'=>$id
                ]);
            } catch (Throwable $e) {}
            flash('success','Thank you. Our team will review this listing.');
            redirect('listing.php?id='.$id);
        }

        throw new Exception('Report module is not ready. Please contact support.');
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
}

$reasons = $isCompany
    ? ['Wrong contact details','Fake company','Scam suspected','Duplicate company','Wrong category','Closed business','Offensive content','Suspicious website','Other']
    : ['Scam','Duplicate','Wrong category','Fake item','Prohibited item','Misleading price','Sold but still active','Offensive content','Contact details abuse','Spam','Other'];

include __DIR__.'/includes/header.php';
?>
<section class="mj-section">
  <div class="container">
    <div class="mj-card p-4 mx-auto" style="max-width:760px">
      <?php show_flash(); ?>
      <span class="mj-badge mb-2"><i class="bi bi-shield-exclamation"></i> Marketplace safety</span>
      <h1 class="fw-bold"><?=e($pageTitle)?></h1>
      <p class="text-muted">Tell us what is wrong. Reports help keep MJ Marketplace safe and useful for everyone.</p>
      <form method="post">
        <?=csrf_input()?>
        <input type="hidden" name="type" value="<?=e($type)?>">
        <input type="hidden" name="id" value="<?=e($id)?>">

        <label class="form-label fw-semibold">Reason</label>
        <select class="form-select" name="reason" required>
          <?php foreach($reasons as $r): ?><option><?=e($r)?></option><?php endforeach; ?>
        </select>

        <label class="form-label fw-semibold mt-3">Details</label>
        <textarea class="form-control" name="message" rows="5" maxlength="1000" placeholder="Add details so our team can review faster."></textarea>

        <div class="alert alert-light border rounded-4 mt-3 small text-muted">
          Please do not include passwords, OTP, bank login, or sensitive personal information in your report.
        </div>

        <button class="btn btn-danger mt-2"><i class="bi bi-flag me-1"></i>Submit Report</button>
        <a class="btn btn-outline-secondary mt-2" href="<?=e($isCompany ? base_url('company.php?id='.$id) : base_url('listing.php?id='.$id))?>">Cancel</a>
      </form>
    </div>
  </div>
</section>
<?php include __DIR__.'/includes/footer.php'; ?>
