<?php
require_once 'config/config.php';
require_once 'includes/functions.php';
startSecureSession();
$pageTitle = 'Repair Request';

$sent = false;
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = sanitize($_POST['contact_name'] ?? '');
    $email    = sanitize($_POST['contact_email'] ?? '');
    $phone    = sanitize($_POST['phone'] ?? '');
    $machine  = sanitize($_POST['machine_type'] ?? '');
    $model    = sanitize($_POST['make_model'] ?? '');
    $serial   = sanitize($_POST['serial_number'] ?? '');
    $issue    = sanitize($_POST['issue_description'] ?? '');
    $urgency  = in_array($_POST['urgency'] ?? '', ['normal','urgent','emergency']) ? $_POST['urgency'] : 'normal';

    if (!$name || !$email || !$machine || !$issue) {
        $errors[] = 'Name, email, machine type, and issue description are required.';
    } else {
        // Handle photo uploads
        $photos = [];
        if (!empty($_FILES['photos']['tmp_name'][0])) {
            foreach ($_FILES['photos']['tmp_name'] as $i => $tmp) {
                if (!$tmp) continue;
                $fileArr = [
                    'tmp_name' => $tmp, 'name' => $_FILES['photos']['name'][$i],
                    'error' => $_FILES['photos']['error'][$i], 'size' => $_FILES['photos']['size'][$i],
                    'type' => $_FILES['photos']['type'][$i],
                ];
                $res = handleFileUpload($fileArr, 'repair', ALLOWED_IMAGE_TYPES);
                if ($res['success']) $photos[] = $res['filename'];
            }
        }

        $reqNum = generateNumber('REP-', 'repair_requests', 'request_number');
        $custId = $_SESSION['customer_id'] ?? null;

        Database::insert(
            "INSERT INTO repair_requests (request_number, customer_id, customer_name, customer_email, customer_phone, machine_type, make_model, serial_number, issue_description, urgency, photos)
             VALUES (?,?,?,?,?,?,?,?,?,?,?)",
            [$reqNum, $custId, $name, $email, $phone, $machine, $model, $serial, $issue, $urgency, json_encode($photos)]
        );

        // Notify admin
        sendEmail(setting('email'), "New Repair Request: $reqNum - $machine",
            "<h3>Repair Request $reqNum</h3><p><b>From:</b> $name ($email)<br><b>Phone:</b> $phone<br><b>Machine:</b> $machine $model<br><b>Serial:</b> $serial<br><b>Urgency:</b> $urgency</p><p><b>Issue:</b><br>$issue</p>"
        );

        $sent = true;
    }
}

include 'includes/header.php';
?>

<div class="max-w-4xl mx-auto px-4 py-14">
  <div class="text-center mb-10 fade-in">
    <div class="section-tag">🛠️ Workshop Services</div>
    <h1 class="section-title">Repair Request Form</h1>
    <div class="section-divider mx-auto"></div>
    <p class="text-gray-400">Submit your machine details and our engineers will assess and quote within 24 hours.</p>
  </div>

  <?php if ($sent): ?>
  <div class="card-dark p-10 text-center fade-in">
    <div class="text-6xl mb-4">🛠️</div>
    <h2 class="text-2xl font-bold text-green-400 mb-2">Request Submitted!</h2>
    <p class="text-gray-400 mb-6">Our workshop team will review your request and contact you within 24 hours with an assessment and quote.</p>
    <a href="/" class="btn-primary">Back to Home</a>
  </div>
  <?php else: ?>

  <?php foreach ($errors as $e): ?><div class="bg-red-900 border border-red-600 text-red-200 rounded p-3 text-sm mb-4"><?= e($e) ?></div><?php endforeach; ?>

  <div class="card-dark p-8 fade-in">
    <form method="POST" enctype="multipart/form-data">
      <div class="grid grid-cols-2 gap-5 mb-5">
        <div class="col-span-2 md:col-span-1">
          <label class="text-xs text-gray-400 block mb-1.5">Your Name *</label>
          <input type="text" name="contact_name" required>
        </div>
        <div class="col-span-2 md:col-span-1">
          <label class="text-xs text-gray-400 block mb-1.5">Email *</label>
          <input type="email" name="contact_email" required>
        </div>
        <div class="col-span-2 md:col-span-1">
          <label class="text-xs text-gray-400 block mb-1.5">Phone</label>
          <input type="tel" name="phone">
        </div>
        <div class="col-span-2 md:col-span-1">
          <label class="text-xs text-gray-400 block mb-1.5">Urgency *</label>
          <select name="urgency">
            <option value="normal">Normal</option>
            <option value="urgent">Urgent</option>
            <option value="emergency">Emergency</option>
          </select>
        </div>
      </div>
      <hr class="border-navy-500 my-5">
      <h3 class="font-semibold mb-4 text-orange-400">Machine Details</h3>
      <div class="grid grid-cols-2 gap-5 mb-5">
        <div class="col-span-2">
          <label class="text-xs text-gray-400 block mb-1.5">Machine Type *</label>
          <input type="text" name="machine_type" required placeholder="e.g. Excavator, Hydraulic Pump, Jaw Crusher...">
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Make / Model</label>
          <input type="text" name="make_model" placeholder="e.g. Caterpillar 320D">
        </div>
        <div>
          <label class="text-xs text-gray-400 block mb-1.5">Serial Number</label>
          <input type="text" name="serial_number">
        </div>
        <div class="col-span-2">
          <label class="text-xs text-gray-400 block mb-1.5">Issue Description *</label>
          <textarea name="issue_description" rows="5" required placeholder="Describe the fault, symptoms, and any previous repair history..."></textarea>
        </div>
        <div class="col-span-2">
          <label class="text-xs text-gray-400 block mb-1.5">Photos (up to 5, max 10MB each)</label>
          <input type="file" name="photos[]" accept="image/*" multiple style="width:auto">
          <p class="text-xs text-gray-500 mt-1">Photos help our engineers provide a more accurate assessment.</p>
        </div>
      </div>
      <button type="submit" class="btn-primary w-full py-3">Submit Repair Request →</button>
    </form>
  </div>
  <?php endif; ?>
</div>

<?php include 'includes/footer.php'; ?>
