<?php
session_start();
require_once __DIR__ . '/config.php';
ensure_schema();
require_admin();
$pdo = db();

$id = (int)($_GET['id'] ?? 0);
$st = $pdo->prepare("SELECT r.*, u.username FROM requests r JOIN users u ON u.id=r.user_id WHERE r.id=? LIMIT 1");
$st->execute([$id]);
$r = $st->fetch();
if(!$r){ http_response_code(404); echo "Not found"; exit; }

$modsSt = $pdo->prepare("SELECT m.* FROM request_mods rm JOIN modifications m ON m.id=rm.mod_id WHERE rm.request_id=? ORDER BY m.category,m.sort_order,m.id");
$modsSt->execute([$id]);
$ml = $modsSt->fetchAll();

$err = '';
$ok = '';

function safe_decimal($x){
  $x = str_replace(',', '.', trim((string)$x));
  if($x === '') return null;
  if(!preg_match('/^-?\d+(\.\d{1,2})?$/', $x)) return null;
  return (float)$x;
}

if($_SERVER['REQUEST_METHOD']==='POST'){
  $action = $_POST['action'] ?? '';

  if($action === 'accept'){
    $pdo->prepare("UPDATE requests SET status='PROCESSING', updated_at=NOW() WHERE id=? AND status IN ('PENDING')")->execute([$id]);
    $ok = 'Status updated: PROCESSING';
  }
  elseif($action === 'reject'){
    $pdo->prepare("UPDATE requests SET status='REJECTED', updated_at=NOW() WHERE id=?")->execute([$id]);
    $ok = 'Status updated: REJECTED';
  }
  elseif($action === 'update_meta'){
    $ap = safe_decimal($_POST['admin_price'] ?? '');
    $pay = $_POST['payment_status'] ?? 'UNPAID';
    if(!in_array($pay, ['UNPAID','PAID'], true)) $pay = 'UNPAID';

    $pdo->prepare("UPDATE requests SET admin_price=?, payment_status=?, updated_at=NOW() WHERE id=?")->execute([$ap, $pay, $id]);
    $ok = 'Saved.';
  }
  elseif($action === 'upload_result'){
    if(empty($_FILES['result_file']['name']) || (int)$_FILES['result_file']['error']!==0){
      $err = 'MOD file required.';
    } else {
      $maxBytes = MAX_UPLOAD_MB*1024*1024;
      if((int)$_FILES['result_file']['size'] > $maxBytes) $err = 'File too large. Max '.MAX_UPLOAD_MB.'MB';
      else{
        $orig = basename($_FILES['result_file']['name']);
        $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION)); if($ext==='') $ext='bin';
        $stored = 'mod_'.$id.'_'.time().'_'.bin2hex(random_bytes(4)).'.'.$ext;
        if(!is_dir(UPLOAD_DIR)) @mkdir(UPLOAD_DIR,0775,true);
        $dest = UPLOAD_DIR.'/'.$stored;

        if(!move_uploaded_file($_FILES['result_file']['tmp_name'], $dest)){
          $err = 'Upload failed (check folder permissions).';
        } else {
          $pdo->prepare("UPDATE requests SET result_original_filename=?, result_stored_filename=?, status='COMPLETED', updated_at=NOW() WHERE id=?")->execute([$orig,$stored,$id]);
          $ok = 'MOD uploaded. Status set to COMPLETED.';
        }
      }
    }
  }

  // Reload request
  $st->execute([$id]); $r = $st->fetch();
}

?>
<!doctype html><html lang="tr"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo h(APP_NAME); ?> • Admin • Request #<?php echo (int)$r['id']; ?></title>
<link rel="stylesheet" href="<?php echo h(BASE_URL); ?>/assets/css/app.css"></head>
<body class="frameGlow"><div class="bgDots"></div><div class="network"></div>

<div style="max-width:1200px;margin:5vh auto;padding:24px;position:relative;z-index:2">
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
    <a class="btnLink" href="<?php echo h(BASE_URL); ?>/admin_requests.php" style="padding:8px 10px">← Back</a>
    <div style="display:flex;gap:10px;align-items:center">
      <span class="badge warn">#<?php echo (int)$r['id']; ?></span>
      <?php
        $cls='warn';
        if($r['status']==='COMPLETED') $cls='ok';
        elseif($r['status']==='PROCESSING') $cls='teal';
        elseif($r['status']==='REJECTED') $cls='bad';
      ?>
      <span class="badge <?php echo $cls; ?>"><?php echo h($r['status']); ?></span>
      <?php $pcls = (($r['payment_status']??'UNPAID')==='PAID') ? 'ok' : 'warn'; ?>
      <span class="badge <?php echo $pcls; ?>"><?php echo h($r['payment_status']??'UNPAID'); ?></span>
      <a class="btnLink" href="<?php echo h(BASE_URL); ?>/admin_logout.php" style="padding:8px 10px">Çıkış</a>
    </div>
  </div>

  <?php if($err): ?><div class="note" style="border-color:rgba(255,120,120,.35);background:rgba(255,120,120,.07)"><?php echo h($err); ?></div><?php endif; ?>
  <?php if($ok): ?><div class="note" style="border-color:rgba(120,255,160,.25);background:rgba(120,255,160,.06)"><?php echo h($ok); ?></div><?php endif; ?>

  <div class="card">
    <div class="cardHeader"><div class="cardTitle"><span class="ico"></span> Request Detail</div></div>
    <div class="body">
      <div class="row">
        <div class="field"><label>User</label><div class="input"><?php echo h($r['username']); ?></div></div>
        <div class="field"><label>Created</label><div class="input"><?php echo h($r['created_at']); ?></div></div>
      </div>
      <div class="row">
        <div class="field"><label>Make & Model</label><div class="input"><?php echo h(trim(($r['manufacturer']??'').' '.($r['model']??''))); ?></div></div>
        <div class="field"><label>Engine</label><div class="input"><?php echo h($r['engine']?:'-'); ?></div></div>
      </div>
      <div class="row">
        <div class="field"><label>ECU</label><div class="input"><?php echo h($r['ecu']?:'-'); ?></div></div>
        <div class="field"><label>Device</label><div class="input"><?php echo h($r['device']?:'-'); ?></div></div>
      </div>

      <div class="field"><label>Requested Modifications</label>
        <div class="input" style="height:auto">
          <?php if(!$ml): ?><small>No options selected.</small>
          <?php else: foreach($ml as $m): ?>
            <span class="badge teal" style="margin:4px 6px 0 0;display:inline-flex"><?php echo h($m['name']); ?></span>
          <?php endforeach; endif; ?>
        </div>
      </div>

      <div class="field"><label>Notes</label><div class="input" style="height:auto"><?php echo nl2br(h($r['notes']?:'-')); ?></div></div>

      <div class="hr"></div>

      <div class="row">
        <div class="field"><label>ORI file</label>
          <div class="input"><?php echo h($r['original_filename']); ?></div>
          <a class="btnLink" href="<?php echo h(BASE_URL); ?>/download.php?type=ori&id=<?php echo (int)$r['id']; ?>" style="margin-top:10px">Download ORI</a>
        </div>

        <div class="field"><label>MOD file</label>
          <div class="input"><?php echo h($r['result_original_filename']?:'-'); ?></div>
          <?php if(!empty($r['result_stored_filename'])): ?>
            <a class="btnLink" href="<?php echo h(BASE_URL); ?>/download.php?type=mod&id=<?php echo (int)$r['id']; ?>" style="margin-top:10px">Download MOD</a>
          <?php else: ?>
            <small>Henüz yüklenmedi.</small>
          <?php endif; ?>
        </div>
      </div>

      <div class="hr"></div>

      <div class="row">
        <div class="field">
          <form method="post" style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
            <input type="hidden" name="action" value="update_meta">
            <div style="flex:1;min-width:240px">
              <label>Custom price (admin_price)</label>
              <input class="input" name="admin_price" value="<?php echo h($r['admin_price']===null?'':$r['admin_price']); ?>" placeholder="e.g. 100.00" />
            </div>
            <div style="width:240px">
              <label>Payment status</label>
              <select class="input" name="payment_status">
                <?php foreach(['UNPAID','PAID'] as $p): ?>
                  <option value="<?php echo h($p); ?>" <?php echo (($r['payment_status']??'UNPAID')===$p)?'selected':''; ?>><?php echo h($p); ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div style="width:160px">
              <label>&nbsp;</label>
              <button class="btnLink" type="submit" style="width:100%;justify-content:center">Save</button>
            </div>
          </form>
        </div>

        <div class="field">
          <label>Status actions</label>
          <div style="display:flex;gap:10px;flex-wrap:wrap">
            <form method="post"><input type="hidden" name="action" value="accept"><button class="btnLink" type="submit">Accept → PROCESSING</button></form>
            <form method="post"><input type="hidden" name="action" value="reject"><button class="btnLink" type="submit" style="border-color:rgba(255,120,120,.35)">Reject → REJECTED</button></form>
          </div>
          <small>Upload MOD → otomatik COMPLETED</small>
        </div>
      </div>

      <div class="hr"></div>

      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="action" value="upload_result">
        <div class="row">
          <div class="field" style="flex:1">
            <label>Result MOD file upload</label>
            <input class="input" type="file" name="result_file" required>
            <small>Yükleyince status otomatik COMPLETED olur.</small>
          </div>
          <div class="field" style="width:220px;align-self:flex-end">
            <button class="btnLink" type="submit" style="width:100%;justify-content:center">Upload</button>
          </div>
        </div>
      </form>

    </div>
  </div>
</div>
</body></html>
