<?php
session_start();
require_once __DIR__ . '/config.php';
ensure_schema();
require_user();

$pdo=db();
$mods=$pdo->query("SELECT * FROM modifications WHERE active=1 ORDER BY category, sort_order, id")->fetchAll();
$groups=['STAGE'=>[],'EMISSION'=>[],'FEATURE'=>[]];
foreach($mods as $m){ $groups[$m['category']][]=$m; }

$err='';

if($_SERVER['REQUEST_METHOD']==='POST'){
  $manufacturer=trim($_POST['manufacturer']??'');
  $model=trim($_POST['model']??'');
  $generation=trim($_POST['generation']??'');
  $engine=trim($_POST['engine']??'');
  $ecu=trim($_POST['ecu']??'');
  $device=trim($_POST['device']??'');
  $notes=trim($_POST['notes']??'');
  $priority=$_POST['priority']??'NORMAL';
  $modsSel=$_POST['mods']??[];

  if($manufacturer===''||$model===''||$ecu==='') $err='Manufacturer / Model / ECU zorunlu.';
  elseif(!in_array($priority,['NORMAL','FAST','URGENT'],true)) $err='Priority hatalı.';
  elseif(empty($_FILES['ecu_file']['name']) || (int)$_FILES['ecu_file']['error']!==0) $err='ECU dosyası zorunlu.';
  else{
    $maxBytes=MAX_UPLOAD_MB*1024*1024;
    if((int)$_FILES['ecu_file']['size']>$maxBytes) $err='Dosya çok büyük. Max '.MAX_UPLOAD_MB.'MB';
    else{
      $orig=basename($_FILES['ecu_file']['name']);
      $ext=strtolower(pathinfo($orig, PATHINFO_EXTENSION)); if($ext==='') $ext='bin';
      $stored='req_'.(int)$_SESSION['user_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['ecu_file']['tmp_name'],$dest)) $err='Upload başarısız (izinleri kontrol et).';
      else{
        $selIds=array_values(array_filter(array_map('intval',(array)$modsSel)));
        $sum=0.0;
        if($selIds){
          $in=implode(',', array_fill(0,count($selIds),'?'));
          $st=$pdo->prepare("SELECT SUM(credit) s FROM modifications WHERE id IN ($in)");
          $st->execute($selIds);
          $sum=(float)($st->fetch()['s']??0);
        }
        if($priority==='FAST') $sum+=10.0;
        if($priority==='URGENT') $sum+=30.0;

        $st=$pdo->prepare("INSERT INTO requests
          (user_id,manufacturer,model,generation,engine,ecu,device,priority,notes,original_filename,stored_filename,total_credit,status,created_at)
          VALUES (?,?,?,?,?,?,?,?,?,?,?,?, 'PENDING', NOW())");
        $st->execute([(int)$_SESSION['user_id'],$manufacturer,$model,$generation,$engine,$ecu,$device,$priority,$notes,$orig,$stored,$sum]);
        $rid=(int)$pdo->lastInsertId();

        if($selIds){
          $st2=$pdo->prepare("INSERT IGNORE INTO request_mods(request_id,mod_id) VALUES (?,?)");
          foreach($selIds as $mid) $st2->execute([$rid,$mid]);
        }
        header("Location: ".BASE_URL."/request_view.php?id=".$rid); exit;
      }
    }
  }
}
?>
<!doctype html><html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo h(APP_NAME); ?> • New Request</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 class="app">
  <aside class="sidebar">
    <div class="brand"><div class="mark"></div><div><div class="title"><?php echo h(APP_NAME); ?></div><div class="sub"><?php echo h(APP_SUB); ?></div></div></div>
    <div class="sectionTitle">Main Menu</div>
    <a class="navItem active" href="<?php echo h(BASE_URL); ?>/request_new.php"><span class="ico"></span><span>New Request</span></a>
    <a class="navItem" href="<?php echo h(BASE_URL); ?>/dashboard.php"><span class="ico"></span><span>My Requests</span></a>
    <div class="sectionTitle">Support</div>
    <a class="navItem" href="#"><span class="ico"></span><span>Help & FAQ</span></a>
    <a class="navItem" href="#"><span class="ico"></span><span>My Tickets</span></a>
    <div class="balance">
      <div style="color:rgba(155,176,208,.85);font-size:12px">Your Balance</div>
      <b>6,343 <span style="font-size:12px;color:rgba(155,176,208,.85)">CR</span></b>
      <a class="btnLink" href="<?php echo h(BASE_URL); ?>/logout.php"><span class="ico"></span><span>Log out</span></a>
    </div>
  </aside>

  <main class="main">
    <header class="topbar">
      <div class="search"><span class="ico"></span><input placeholder="Search requests..." /></div>
      <div class="pills">
        <div class="pill">EN 🌐</div><div class="pill">☀️</div><div class="pill">🔔</div>
        <div class="pill"><div><div style="font-weight:950;font-size:12px">System User</div><div style="color:rgba(155,176,208,.8);font-size:11px"><?php echo h($_SESSION['username']??'user'); ?></div></div><div class="avatar">SU</div></div>
      </div>
    </header>

    <div class="content">
      <div style="display:flex;justify-content:space-between;align-items:flex-end;gap:14px;flex-wrap:wrap">
        <div><div class="h1">New File Request</div><div class="subtitle">Vehicle identity + ECU file upload + tuning matrix</div></div>
        <span class="badge teal">WIZARD</span>
      </div>

      <?php if($err): ?>
      <div class="card" style="margin-top:14px"><div class="body"><span class="badge warn"><?php echo h($err); ?></span></div></div>
      <?php endif; ?>

      <form method="post" enctype="multipart/form-data">
        <div class="grid2">
          <section class="card">
            <div class="cardHeader"><div class="cardTitle"><span class="ico"></span> Vehicle Identity</div><span class="badge">required</span></div>
            <div class="body">
              <div class="row">
                <div class="field"><label>Manufacturer *</label><input class="input" name="manufacturer" value="<?php echo h($_POST['manufacturer']??''); ?>" required></div>
                <div class="field"><label>Model *</label><input class="input" name="model" value="<?php echo h($_POST['model']??''); ?>" required></div>
              </div>
              <div class="row">
                <div class="field"><label>Generation</label><input class="input" name="generation" value="<?php echo h($_POST['generation']??''); ?>"></div>
                <div class="field"><label>Engine</label><input class="input" name="engine" value="<?php echo h($_POST['engine']??''); ?>"></div>
              </div>
              <div class="row">
                <div class="field"><label>ECU Type *</label><input class="input" name="ecu" value="<?php echo h($_POST['ecu']??''); ?>" required></div>
                <div class="field"><label>Reading Device</label>
                  <select class="input" name="device"><?php $dv=$_POST['device']??''; ?>
                    <option value="">Select</option>
                    <?php foreach(['Flex','AutoTuner','KESS','KTAG','CMD','Galetto','Other'] as $o): ?>
                      <option <?php echo ($dv===$o?'selected':''); ?>><?php echo h($o); ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
              </div>
              <div class="field"><label>Notes</label><textarea name="notes" placeholder="Extra notes..."><?php echo h($_POST['notes']??''); ?></textarea></div>
              <div class="hr"></div>
              <div style="text-align:center;color:rgba(155,176,208,.85);padding:18px 10px"><div style="opacity:.75">Awaiting configuration...</div></div>
            </div>
          </section>

          <section class="card">
            <div class="cardHeader"><div class="cardTitle"><span class="ico"></span> Upload ECU File</div><span class="badge">matrix</span></div>
            <div class="body">
              <div class="drop" id="dropZone">
                <div style="font-weight:950">Upload ECU File</div>
                <div id="fileLabel" style="margin-top:6px">Drag & drop or click</div>
                <small>BIN / ORI / MOD • up to <?php echo (int)MAX_UPLOAD_MB; ?>MB</small>
                <input id="ecuFile" type="file" name="ecu_file" style="opacity:0;position:absolute;left:-9999px" accept=".bin,.ori,.mod,.zip,.rar,.7z">
                <div style="margin-top:12px"><button type="button" class="prBtn" onclick="document.getElementById('ecuFile').click()">Choose File</button></div>
              </div>

              <div style="margin-top:14px;display:flex;justify-content:space-between;gap:12px;align-items:center">
                <div style="font-weight:950">Tuning Matrix</div>
                <div class="badge">TOTAL <b><span id="totalCredit">0.00</span> CR</b></div>
              </div>

              <div class="matrixSearch" style="margin-top:10px"><span class="ico"></span><input id="matrixSearch" placeholder="Search tuning options..."></div>

              <input type="hidden" id="totalCreditInput" name="total_credit" value="0">
              <input type="hidden" id="priorityInput" name="priority" value="NORMAL">

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

              <?php
              $render=function($title,$list,$badge){
                echo '<div style="margin:10px 0 6px;font-weight:950">'.$title.'</div>';
                echo '<div class="gridCards">';
                foreach($list as $m){
                  $id=(int)$m['id']; $name=$m['name']; $cr=(float)$m['credit'];
                  echo '<div class="opt" data-name="'.h($name).'" data-credit="'.h($cr).'">';
                  echo '<div class="name">'.h($name).'</div>';
                  echo '<div class="meta"><span class="badge '.$badge.'">'.h($m['category']).'</span></div>';
                  echo '<div class="cr">'.h(number_format($cr,2)).' CR</div>';
                  echo '<input type="checkbox" name="mods[]" value="'.$id.'" style="display:none">';
                  echo '</div>';
                }
                echo '</div>';
              };
              $render('Tuning Stages',$groups['STAGE'],'teal');
              $render('Emission Solutions',$groups['EMISSION'],'warn');
              $render('Features & Comfort',$groups['FEATURE'],'');
              ?>

              <div class="hr"></div>
              <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
                <div style="font-weight:950">Request Priority</div>
                <button type="button" class="prBtn active" data-pr="NORMAL">Normal</button>
                <button type="button" class="prBtn" data-pr="FAST">Fast +10 CR</button>
                <button type="button" class="prBtn" data-pr="URGENT">Urgent +30 CR</button>
              </div>

              <button class="bigBtn" type="submit">Initialize Request</button>
              <div class="note">Secure Transaction • server-side validation • stored in MySQL</div>
            </div>
          </section>
        </div>
      </form>
    </div>
  </main>
</div>

<script src="<?php echo h(BASE_URL); ?>/assets/js/app.js"></script>
<script>(function(){const f=document.getElementById('ecuFile'),d=document.getElementById('dropZone');if(!f||!d)return;d.addEventListener('click',()=>f.click());})();</script>
</body></html>
