<?php
/**
 * Admin Order Details Page
 * Detailed view of a single order
 */

$pageTitle = 'Detalii comandă';

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../../includes/Order.php';
require_once __DIR__ . '/../../includes/User.php';

$db = Database::getInstance();
$order = new Order();
$user = new User();

$orderId = intval($_GET['order_id'] ?? 0);
if (!$orderId) {
    header('Location: /admin/comenzi');
    exit;
}

// Get order details
$orderDetails = $db->fetchOne(
    "SELECT o.*, u.first_name, u.last_name, u.email, u.phone
     FROM orders o
     LEFT JOIN users u ON o.user_id = u.id
     WHERE o.id = ?",
    [$orderId]
);

if (!$orderDetails) {
    header('Location: /admin/comenzi');
    exit;
}

// Get order items
$orderItems = $order->getOrderItems($orderId);

// Get addresses
$shippingAddress = $user->getAddressById($orderDetails['shipping_address_id']);
$billingAddress = $user->getAddressById($orderDetails['billing_address_id']);

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_status') {
    $newStatus = $_POST['status'] ?? '';
    if ($newStatus) {
        $db->execute(
            "UPDATE orders SET order_status = ?, updated_at = NOW() WHERE id = ?",
            [$newStatus, $orderId]
        );
        header('Location: /admin/comenzi/' . $orderId . '?updated=1');
        exit;
    }
}

$statusText = [
    'pending' => 'În așteptare',
    'processing' => 'În procesare',
    'shipped' => 'Expediată',
    'delivered' => 'Livrată',
    'canceled' => 'Anulată'
];

$statusClass = [
    'pending' => 'warning',
    'processing' => 'primary',
    'shipped' => 'info',
    'delivered' => 'success',
    'canceled' => 'danger'
];
?>

<div class="content">
  <div class="px-3 px-xxl-4 py-3 py-lg-4">
    <div class="card mb-3">
      <div class="card-body">
        <div class="row flex-between-center">
          <div class="col-auto">
            <h5>Detalii comandă: <?php echo htmlspecialchars($orderDetails['order_number']); ?></h5>
            <p class="fs-10 mb-0"><?php echo date('d.m.Y H:i', strtotime($orderDetails['created_at'])); ?></p>
          </div>
          <div class="col-auto">
            <form method="POST" class="d-inline">
              <input type="hidden" name="action" value="update_status">
              <div class="d-flex align-items-center gap-2">
                <strong class="me-2">Status: </strong>
                <select name="status" class="form-select form-select-sm" onchange="this.form.submit()">
                  <option value="pending" <?php echo ($orderDetails['order_status'] === 'pending') ? 'selected' : ''; ?>>În așteptare</option>
                  <option value="processing" <?php echo ($orderDetails['order_status'] === 'processing') ? 'selected' : ''; ?>>În procesare</option>
                  <option value="shipped" <?php echo ($orderDetails['order_status'] === 'shipped') ? 'selected' : ''; ?>>Expediată</option>
                  <option value="delivered" <?php echo ($orderDetails['order_status'] === 'delivered') ? 'selected' : ''; ?>>Livrată</option>
                  <option value="canceled" <?php echo ($orderDetails['order_status'] === 'canceled') ? 'selected' : ''; ?>>Anulată</option>
                </select>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-body">
        <div class="row">
          <div class="col-md-6 col-lg-4 mb-4 mb-lg-0">
            <h5 class="mb-3 fs-9">Adresă facturare</h5>
            <?php if ($billingAddress): ?>
            <h6 class="mb-2"><?php echo htmlspecialchars($billingAddress['first_name'] . ' ' . $billingAddress['last_name']); ?></h6>
            <p class="mb-1 fs-10">
              <?php echo htmlspecialchars($billingAddress['address_line1']); ?><br>
              <?php if ($billingAddress['address_line2']): ?>
              <?php echo htmlspecialchars($billingAddress['address_line2']); ?><br>
              <?php endif; ?>
              <?php echo htmlspecialchars($billingAddress['city'] . ', ' . $billingAddress['county'] . ' ' . $billingAddress['postcode']); ?>
            </p>
            <?php if ($billingAddress['email']): ?>
            <p class="mb-0 fs-10"><strong>Email: </strong><a href="mailto:<?php echo htmlspecialchars($billingAddress['email']); ?>"><?php echo htmlspecialchars($billingAddress['email']); ?></a></p>
            <?php endif; ?>
            <?php if ($billingAddress['phone']): ?>
            <p class="mb-0 fs-10"><strong>Telefon: </strong><a href="tel:<?php echo htmlspecialchars($billingAddress['phone']); ?>"><?php echo htmlspecialchars($billingAddress['phone']); ?></a></p>
            <?php endif; ?>
            <?php else: ?>
            <p class="text-600">Adresă de facturare indisponibilă</p>
            <?php endif; ?>
          </div>
          <div class="col-md-6 col-lg-4 mb-4 mb-lg-0">
            <h5 class="mb-3 fs-9">Adresă livrare</h5>
            <?php if ($shippingAddress): ?>
            <h6 class="mb-2"><?php echo htmlspecialchars($shippingAddress['first_name'] . ' ' . $shippingAddress['last_name']); ?></h6>
            <p class="mb-1 fs-10">
              <?php echo htmlspecialchars($shippingAddress['address_line1']); ?><br>
              <?php if ($shippingAddress['address_line2']): ?>
              <?php echo htmlspecialchars($shippingAddress['address_line2']); ?><br>
              <?php endif; ?>
              <?php echo htmlspecialchars($shippingAddress['city'] . ', ' . $shippingAddress['county'] . ' ' . $shippingAddress['postcode']); ?>
            </p>
            <?php if ($shippingAddress['email']): ?>
            <p class="mb-0 fs-10"><strong>Email: </strong><a href="mailto:<?php echo htmlspecialchars($shippingAddress['email']); ?>"><?php echo htmlspecialchars($shippingAddress['email']); ?></a></p>
            <?php endif; ?>
            <?php if ($shippingAddress['phone']): ?>
            <p class="mb-0 fs-10"><strong>Telefon: </strong><a href="tel:<?php echo htmlspecialchars($shippingAddress['phone']); ?>"><?php echo htmlspecialchars($shippingAddress['phone']); ?></a></p>
            <?php endif; ?>
            <?php else: ?>
            <p class="text-600">Adresă de livrare indisponibilă</p>
            <?php endif; ?>
          </div>
          <div class="col-md-6 col-lg-4">
            <h5 class="mb-3 fs-9">Metodă plată</h5>
            <div class="d-flex align-items-center">
              <div class="flex-1">
                <h6 class="mb-0">
                  <?php
                  switch ($orderDetails['payment_method']) {
                      case 'cash_on_delivery':
                          echo 'Ramburs la livrare';
                          break;
                      case 'credit_card':
                          echo 'Card de credit/debit';
                          break;
                      case 'paypal':
                          echo 'PayPal';
                          break;
                      case 'google_pay':
                          echo 'Google Pay';
                          break;
                      default:
                          echo htmlspecialchars($orderDetails['payment_method']);
                  }
                  ?>
                </h6>
              </div>
            </div>
            <?php if ($orderDetails['coupon_code']): ?>
            <p class="mb-0 fs-10 mt-2"><strong>Cupon: </strong><?php echo htmlspecialchars($orderDetails['coupon_code']); ?></p>
            <?php endif; ?>
            <?php if ($orderDetails['loyalty_points_used'] > 0): ?>
            <p class="mb-0 fs-10"><strong>Puncte fidelitate folosite: </strong><?php echo number_format($orderDetails['loyalty_points_used']); ?></p>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>

    <div class="card mb-3">
      <div class="card-body">
        <div class="table-responsive fs-10">
          <table class="table table-striped border-bottom">
            <thead class="bg-200">
              <tr>
                <th class="text-900 border-0">Produs</th>
                <th class="text-900 border-0 text-center">Cantitate</th>
                <th class="text-900 border-0 text-end">Preț unitar</th>
                <th class="text-900 border-0 text-end">Total</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($orderItems as $item): ?>
              <tr class="border-200">
                <td class="align-middle">
                  <h6 class="mb-0 text-nowrap"><?php echo htmlspecialchars($item['product_name']); ?></h6>
                  <?php if ($item['is_gift']): ?>
                  <span class="badge badge-subtle-success">Produs cadou</span>
                  <?php endif; ?>
                </td>
                <td class="align-middle text-center"><?php echo $item['quantity']; ?></td>
                <td class="align-middle text-end"><?php echo number_format($item['price'], 2); ?> RON</td>
                <td class="align-middle text-end"><?php echo number_format($item['subtotal'], 2); ?> RON</td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <div class="row g-0 justify-content-end mt-3">
          <div class="col-auto">
            <table class="table table-sm table-borderless fs-10 text-end">
              <tr>
                <th class="text-900">Subtotal:</th>
                <td class="fw-semi-bold"><?php echo number_format($orderDetails['subtotal'], 2); ?> RON</td>
              </tr>
              <?php if ($orderDetails['discount'] > 0): ?>
              <tr>
                <th class="text-900">Reducere:</th>
                <td class="fw-semi-bold text-success">-<?php echo number_format($orderDetails['discount'], 2); ?> RON</td>
              </tr>
              <?php endif; ?>
              <tr>
                <th class="text-900">Transport:</th>
                <td class="fw-semi-bold"><?php echo number_format($orderDetails['shipping_cost'], 2); ?> RON</td>
              </tr>
              <tr class="border-top">
                <th class="text-900">Total:</th>
                <td class="fw-semi-bold"><?php echo number_format($orderDetails['total'], 2); ?> RON</td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </div>

    <?php if ($orderDetails['notes']): ?>
    <div class="card mb-3">
      <div class="card-body">
        <h6 class="mb-2">Note comandă</h6>
        <p class="mb-0"><?php echo nl2br(htmlspecialchars($orderDetails['notes'])); ?></p>
      </div>
    </div>
    <?php endif; ?>
  </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>

