<?php
include('../db/cn.php');
ob_start();
//session_start();

if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}
@$orderID = $_GET["order_id"];

$userName = $_SESSION['user_name'] ?? 'Guest';
$date = date('Y-m-d');
$message = "";

// Handle form submit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $order_id = $_POST['order_id'] ?? '';
    $date_time = $_POST['date_time'] ?? date('Y-m-d');
    $user_name = $_POST['user_name'] ?? 'Guest';

    if (isset($_FILES['img_upload']) && $_FILES['img_upload']['error'] == 0) {
        $targetDir = "uploads/";
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        $fileName = time() . "_" . basename($_FILES['img_upload']['name']);
        $targetFilePath = $targetDir . $fileName;

        if (move_uploaded_file($_FILES['img_upload']['tmp_name'], $targetFilePath)) {
            $stmt = $connection->prepare("INSERT INTO img_log_sales (order_id, img_upload, date_time, user_name) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $order_id, $fileName, $date_time, $user_name);

            if ($stmt->execute()) {
                $message = "<div class='alert alert-success'>Image uploaded successfully!</div>";
            } else {
                $message = "<div class='alert alert-danger'>Database error: " . $stmt->error . "</div>";
            }
        } else {
            $message = "<div class='alert alert-danger'>File upload failed.</div>";
        }
    } else {
        $message = "<div class='alert alert-warning'>Please upload a valid image.</div>";
    }
}
ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Image Upload - World Diagnostic</title>
  <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

  <style>
    .header {
      background: linear-gradient(90deg, #353535, #0A4657);
      color: white;
      padding: 20px;
      text-align: center;
      font-size: 3.0rem;
      font-weight: bold;
    }
    body {
      background: #f8f9fa;
      font-family: 'Quicksand', sans-serif;
    }
    .card {
      border-radius: 12px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.15);
    }
    label, .form-control {
      font-weight:700;
    }
    .btn-primary {
      background:#0A4657;
      color:#fff;
      border:1px #0A4657 solid;
      font-weight:700;
    }  
    .btn-primary:hover {
      background:#fff;
      border:1px #0A4657 solid;
      color:#0A4657;
      font-weight:700;
    }
  </style>
</head>
<body>

  <div class="header">
    World Diagnostic
    <a href="order_detail_v.php">
      <button class="btn btn-light" style="float:right; font-weight:700; margin-top:20px;">Back</button>
    </a>
  </div>

  <div class="container mt-5">
    <div class="row justify-content-center">
      <div class="col-md-6">
        <div class="card p-4">
          <h1 class="mb-3 text-center font-weight-bold">Upload Image</h1>

          <!-- Show success/error -->
          <?= $message ?>

          <form method="POST" enctype="multipart/form-data">
            <!-- Order ID -->
            <div class="mb-3">
              <label for="order_id" class="form-label">Order ID</label>
              <input type="text" name="order_id" value="<?php echo $orderID; ?>" id="order_id" class="form-control" readonly>
            </div>

            <!-- Image Upload -->
            <div class="mb-3">
              <label for="img_upload" class="form-label">Upload Image</label>
              <input type="file" name="img_upload" id="img_upload" class="form-control" accept="image/*" required>
            </div>

            <!-- Hidden values -->
            <input type="hidden" name="date_time" value="<?= $date ?>">
            <input type="hidden" name="user_name" value="<?= htmlspecialchars($userName) ?>">

            <!-- Submit + View -->
            <div class="d-grid gap-2">
              <!-- Upload Button -->
              <button type="submit" class="btn btn-primary">Upload IMG</button>

              <!-- View Button -->
              <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#viewImgModal">
                View IMG
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

  <!-- Image View Modal -->
  <div class="modal fade" id="viewImgModal" tabindex="-1" aria-labelledby="viewImgModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="viewImgModalLabel">Uploaded Image</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body text-center">
          <?php
            // fetch last uploaded image for this order
            $imgQuery = $connection->prepare("SELECT img_upload FROM img_log_sales WHERE order_id=? ORDER BY id DESC LIMIT 1");
            $imgQuery->bind_param("s", $orderID);
            $imgQuery->execute();
            $imgResult = $imgQuery->get_result();
            $imgRow = $imgResult->fetch_assoc();
            if ($imgRow && !empty($imgRow['img_upload'])) {
                $imgPath = "uploads/" . $imgRow['img_upload'];
                echo "<img src='$imgPath' class='img-fluid rounded shadow'>";
            } else {
                echo "<p class='text-muted'>No image uploaded yet.</p>";
            }
          ?>
        </div>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
