<?php
session_start();
require 'config.php';
if (empty($_SESSION['user'])) header('Location: login.php');
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>💰 تسجيل المبيعات</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background-color: #f8f9fa; }
.card { border-radius: 15px; }
</style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="container py-4">
  <h3 class="text-center mb-4">💰 تسجيل المبيعات</h3>

  <?php
  if ($_SERVER['REQUEST_METHOD']==='POST') {
      $pid = $_POST['product_id'] ?? 0;
      $bags = $_POST['bags_sold'] ?? 0;
      $weight = $_POST['weight_sold'] ?? 0; // الوزن الكلي
      $note = $_POST['note'] ?? '';
      $imagePath = null;

      if (!empty($_FILES['image']['name'])) {
          $file = time() . "_" . basename($_FILES['image']['name']);
          $target = UPLOAD_DIR . $file;
          move_uploaded_file($_FILES['image']['tmp_name'], $target);
          $imagePath = 'uploads/' . $file;
      }

      // حفظ عملية البيع
      $stmt = $pdo->prepare('INSERT INTO sales (product_id, bags_sold, weight_sold, note, image) VALUES (?, ?, ?, ?, ?)');
      $stmt->execute([$pid, $bags, $weight, $note, $imagePath]);

      // خصم الكمية مباشرة من المخزون
      $update = $pdo->prepare('UPDATE stock 
          SET bags_count = bags_count - ?, 
              total_weight = total_weight - ? 
          WHERE product_id = ?');
      $update->execute([$bags, $weight, $pid]);

      echo '<div class="alert alert-success text-center">✅ تم حفظ البيع وتم خصم الكمية من المخزون بنجاح</div>';
  }

  $products = $pdo->query('SELECT id, name FROM products')->fetchAll();
  $sales = $pdo->query('SELECT s.*, p.name FROM sales s JOIN products p ON p.id = s.product_id ORDER BY s.id DESC')->fetchAll();
  ?>

  <form method="post" enctype="multipart/form-data" class="card p-3 mb-4 shadow-sm">
    <div class="row g-2">
      <div class="col-12 col-md-3">
        <select name="product_id" class="form-select" required>
          <option value="">اختر المادة</option>
          <?php foreach ($products as $p): ?>
          <option value="<?=$p['id']?>"><?=$p['name']?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-12 col-md-3">
        <input type="number" name="bags_sold" class="form-control" placeholder="عدد الشوالات" required>
      </div>
      <div class="col-12 col-md-3">
        <input type="number" step="0.01" name="weight_sold" class="form-control" placeholder="الوزن الكلي (كغ)" required>
      </div>
    </div>

    <div class="mt-3">
      <label>ملاحظات:</label>
      <div class="input-group">
        <input name="note" id="noteInput" class="form-control" placeholder="اكتب أو استخدم الميكروفون...">
        <button type="button" id="recordBtn" class="btn btn-danger">🎤 تسجيل</button>
      </div>
    </div>

    <div class="mt-2">
      <label>صورة (اختياري):</label>
      <input type="file" name="image" class="form-control">
    </div>

    <button class="btn btn-warning mt-3 w-100">حفظ البيع</button>
  </form>

  <div class="table-responsive shadow-sm">
  <table class="table table-bordered bg-white text-center align-middle">
  <thead class="table-warning">
  <tr>
    <th>المادة</th>
    <th>عدد الشوالات</th>
    <th>الوزن الكلي (كغ)</th>
    <th>ملاحظات</th>
    <th>صورة</th>
    <th>تاريخ</th>
  </tr>
  </thead>
  <tbody>
  <?php foreach ($sales as $s): ?>
  <tr>
    <td><?=$s['name']?></td>
    <td><?=$s['bags_sold']?></td>
    <td><?=$s['weight_sold']?></td>
    <td><?=$s['note']?></td>
    <td><?php if ($s['image']): ?><a href="<?=$s['image']?>" target="_blank">📷</a><?php endif; ?></td>
    <td><?=$s['sale_date']?></td>
  </tr>
  <?php endforeach; ?>
  </tbody>
  </table>
  </div>

  <a href="index.php" class="btn btn-secondary mt-2 w-100">🏠 رجوع</a>
</div>

<script>
const recordBtn = document.getElementById('recordBtn');
const noteInput = document.getElementById('noteInput');
let recognition;
if ('webkitSpeechRecognition' in window) {
  recognition = new webkitSpeechRecognition();
  recognition.lang = 'ar-SA';
  recognition.continuous = false;
  recognition.interimResults = false;
  recordBtn.addEventListener('click', () => {
    recognition.start();
    recordBtn.textContent = '🎙️ جارٍ التسجيل...';
    recordBtn.disabled = true;
  });
  recognition.onresult = (event) => {
    const transcript = event.results[0][0].transcript;
    noteInput.value += (noteInput.value ? ' ' : '') + transcript;
  };
  recognition.onend = () => {
    recordBtn.textContent = '🎤 تسجيل';
    recordBtn.disabled = false;
  };
} else {
  recordBtn.disabled = true;
  recordBtn.textContent = 'الميكروفون غير مدعوم ⚠️';
}
</script>

</body>
</html>
