<?php
/**
 * Account Orders Page
 * Converted from account-orders.html
 * Displays user's order history
 */

$pageTitle = 'Cartzilla | Cont - Istoric Comenzi';
$pageDescription = 'Cartzilla - Magazin Online E-Commerce';

// Initialize classes BEFORE header to allow redirects
require_once __DIR__ . '/includes/init.php';
$order = new Order();
$userObj = new User();
$auth = new Auth();

// Check if user is logged in
if (!$auth->isLoggedIn()) {
    header('Location: /cont/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
    exit;
}

$userId = $auth->getUserId();
$userData = $userObj->getUserById($userId);

// Now include header (after all redirects are handled)
require_once __DIR__ . '/includes/header.php';

// Get filters
$statusFilter = $_GET['status'] ?? '';
$timeframeFilter = $_GET['timeframe'] ?? 'all-time';

// Get orders
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$orders = $order->getUserOrders($userId, $page, $perPage);

// Apply filters
if ($statusFilter) {
    $orders = array_filter($orders, function($o) use ($statusFilter) {
        return $o['order_status'] === $statusFilter;
    });
}

if ($timeframeFilter !== 'all-time') {
    $now = time();
    $cutoff = match($timeframeFilter) {
        'last-year' => strtotime('-1 year'),
        'last-3-months' => strtotime('-3 months'),
        'last-30-days' => strtotime('-30 days'),
        'last-week' => strtotime('-1 week'),
        default => 0
    };
    $orders = array_filter($orders, function($o) use ($cutoff) {
        return strtotime($o['created_at']) >= $cutoff;
    });
}

// Get order items count for each order
foreach ($orders as &$ord) {
    $orderItems = $order->getOrderItems($ord['id']);
    $ord['items_count'] = count($orderItems);
    $ord['items'] = array_slice($orderItems, 0, 3); // First 3 items for thumbnails
}

// Status labels in Romanian
$statusLabels = [
    'pending' => 'În așteptare',
    'processing' => 'În procesare',
    'shipped' => 'Expediată',
    'delivered' => 'Livrată',
    'cancelled' => 'Anulată',
    'refunded' => 'Rambursată'
];

$statusColors = [
    'pending' => 'warning',
    'processing' => 'info',
    'shipped' => 'primary',
    'delivered' => 'success',
    'cancelled' => 'danger',
    'refunded' => 'secondary'
];
?>

    <!-- Page content -->
    <main class="content-wrapper">
      <div class="container py-5 mt-n2 mt-sm-0">
        <div class="row pt-md-2 pt-lg-3 pb-sm-2 pb-md-3 pb-lg-4 pb-xl-5">

          <!-- Sidebar navigation -->
          <aside class="col-lg-3">
            <div class="offcanvas-lg offcanvas-start pe-lg-0 pe-xl-4" id="accountSidebar">

              <!-- Header -->
              <div class="offcanvas-header d-lg-block py-3 p-lg-0">
                <div class="d-flex align-items-center">
                  <div class="h5 d-flex justify-content-center align-items-center flex-shrink-0 text-primary bg-primary-subtle lh-1 rounded-circle mb-0" style="width: 3rem; height: 3rem">
                    <?php echo strtoupper(mb_substr($userData['first_name'], 0, 1) . mb_substr($userData['last_name'], 0, 1)); ?>
                  </div>
                  <div class="min-w-0 ps-3">
                    <h5 class="h6 mb-1"><?php echo htmlspecialchars($userData['first_name'] . ' ' . $userData['last_name']); ?></h5>
                    <div class="nav flex-nowrap text-nowrap min-w-0">
                      <a class="nav-link animate-underline text-body p-0" href="#bonusesModal" data-bs-toggle="modal">
                        <svg class="text-warning flex-shrink-0 me-2" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"><path d="M1.333 9.667H7.5V16h-5c-.64 0-1.167-.527-1.167-1.167V9.667zm13.334 0v5.167c0 .64-.527 1.167-1.167 1.167h-5V9.667h6.167zM0 5.833V7.5c0 .64.527 1.167 1.167 1.167h.167H7.5v-1-3H1.167C.527 4.667 0 5.193 0 5.833zm14.833-1.166H8.5v3 1h6.167.167C15.473 8.667 16 8.14 16 7.5V5.833c0-.64-.527-1.167-1.167-1.167z"/><path d="M8 5.363a.5.5 0 0 1-.495-.573C7.752 3.123 9.054-.03 12.219-.03c1.807.001 2.447.977 2.447 1.813 0 1.486-2.069 3.58-6.667 3.58zM12.219.971c-2.388 0-3.295 2.27-3.595 3.377 1.884-.088 3.072-.565 3.756-.971.949-.563 1.287-1.193 1.287-1.595 0-.599-.747-.811-1.447-.811z"/><path d="M8.001 5.363c-4.598 0-6.667-2.094-6.667-3.58 0-.836.641-1.812 2.448-1.812 3.165 0 4.467 3.153 4.713 4.819a.5.5 0 0 1-.495.573zM3.782.971c-.7 0-1.448.213-1.448.812 0 .851 1.489 2.403 5.042 2.566C7.076 3.241 6.169.971 3.782.971z"/></svg>
                        <span class="animate-target me-1"><?php echo $userData['loyalty_points'] ?? 0; ?> bonusuri</span>
                        <span class="text-body fw-normal text-truncate">disponibile</span>
                      </a>
                    </div>
                  </div>
                </div>
                <button type="button" class="btn-close d-lg-none" data-bs-dismiss="offcanvas" data-bs-target="#accountSidebar" aria-label="Close"></button>
              </div>

              <!-- Body (Navigation) -->
              <div class="offcanvas-body d-block pt-2 pt-lg-4 pb-lg-0">
                <nav class="list-group list-group-borderless">
                  <a class="list-group-item list-group-item-action d-flex align-items-center pe-none active" href="/cont/comenzi">
                    <i class="ci-shopping-bag fs-base opacity-75 me-2"></i>
                    Comenzi
                    <span class="badge bg-primary rounded-pill ms-auto"><?php echo count($orders); ?></span>
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/wishlist">
                    <i class="ci-heart fs-base opacity-75 me-2"></i>
                    Lista de dorințe
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/plata">
                    <i class="ci-credit-card fs-base opacity-75 me-2"></i>
                    Metode de plată
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/recenzii">
                    <i class="ci-star fs-base opacity-75 me-2"></i>
                    Recenziile mele
                  </a>
                </nav>
                <h6 class="pt-4 ps-2 ms-1">Gestionează contul</h6>
                <nav class="list-group list-group-borderless">
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/info">
                    <i class="ci-user fs-base opacity-75 me-2"></i>
                    Informații personale
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/adrese">
                    <i class="ci-map-pin fs-base opacity-75 me-2"></i>
                    Adrese
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/cont/notificari">
                    <i class="ci-bell fs-base opacity-75 mt-1 me-2"></i>
                    Notificări
                  </a>
                </nav>
                <h6 class="pt-4 ps-2 ms-1">Servicii clienți</h6>
                <nav class="list-group list-group-borderless">
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/contact">
                    <i class="ci-help-circle fs-base opacity-75 me-2"></i>
                    Centru de ajutor
                  </a>
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/terms-and-conditions">
                    <i class="ci-info fs-base opacity-75 me-2"></i>
                    Termeni și condiții
                  </a>
                </nav>
                <nav class="list-group list-group-borderless pt-3">
                  <a class="list-group-item list-group-item-action d-flex align-items-center" href="/api/auth.php?action=logout">
                    <i class="ci-log-out fs-base opacity-75 me-2"></i>
                    Deconectare
                  </a>
                </nav>
              </div>
            </div>
          </aside>


          <!-- Orders content -->
          <div class="col-lg-9">
            <div class="ps-lg-3 ps-xl-0">

              <!-- Page title + Sorting selects -->
              <div class="row align-items-center pb-3 pb-md-4 mb-md-1 mb-lg-2">
                <div class="col-md-4 col-xl-6 mb-3 mb-md-0">
                  <h1 class="h2 me-3 mb-0">Comenzi</h1>
                </div>
                <div class="col-md-8 col-xl-6">
                  <form method="GET" class="row row-cols-1 row-cols-sm-2 g-3 g-xxl-4">
                    <div class="col">
                      <select class="form-select" name="status" onchange="this.form.submit()">
                        <option value="">Selectează status</option>
                        <option value="pending" <?php echo $statusFilter === 'pending' ? 'selected' : ''; ?>>În așteptare</option>
                        <option value="processing" <?php echo $statusFilter === 'processing' ? 'selected' : ''; ?>>În procesare</option>
                        <option value="shipped" <?php echo $statusFilter === 'shipped' ? 'selected' : ''; ?>>Expediată</option>
                        <option value="delivered" <?php echo $statusFilter === 'delivered' ? 'selected' : ''; ?>>Livrată</option>
                        <option value="cancelled" <?php echo $statusFilter === 'cancelled' ? 'selected' : ''; ?>>Anulată</option>
                      </select>
                    </div>
                    <div class="col">
                      <select class="form-select" name="timeframe" onchange="this.form.submit()">
                        <option value="all-time" <?php echo $timeframeFilter === 'all-time' ? 'selected' : ''; ?>>Toate</option>
                        <option value="last-year" <?php echo $timeframeFilter === 'last-year' ? 'selected' : ''; ?>>Ultimul an</option>
                        <option value="last-3-months" <?php echo $timeframeFilter === 'last-3-months' ? 'selected' : ''; ?>>Ultimele 3 luni</option>
                        <option value="last-30-days" <?php echo $timeframeFilter === 'last-30-days' ? 'selected' : ''; ?>>Ultimele 30 zile</option>
                        <option value="last-week" <?php echo $timeframeFilter === 'last-week' ? 'selected' : ''; ?>>Ultima săptămână</option>
                      </select>
                    </div>
                  </form>
                </div>
              </div>


              <!-- Orders table -->
              <div>
                <table class="table align-middle fs-sm text-nowrap">
                  <thead>
                    <tr>
                      <th scope="col" class="py-3 ps-0">
                        <span class="text-body fw-normal">Comandă <span class="d-none d-md-inline">#</span></span>
                      </th>
                      <th scope="col" class="py-3 d-none d-md-table-cell">
                        <span class="text-body fw-normal">Data comenzii</span>
                      </th>
                      <th scope="col" class="py-3 d-none d-md-table-cell">
                        <span class="text-body fw-normal">Status</span>
                      </th>
                      <th scope="col" class="py-3 d-none d-md-table-cell">
                        <span class="text-body fw-normal">Total</span>
                      </th>
                      <th scope="col" class="py-3">&nbsp;</th>
                    </tr>
                  </thead>
                  <tbody class="text-body-emphasis">
                    <?php if (empty($orders)): ?>
                    <tr>
                      <td colspan="5" class="text-center py-5">
                        <p class="text-body-secondary mb-0">Nu ai comenzi.</p>
                        <a class="btn btn-primary mt-3" href="/catalog">Începe să cumperi</a>
                      </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($orders as $ord): ?>
                    <tr>
                      <td class="fw-medium pt-2 pb-3 py-md-2 ps-0">
                        <a class="d-inline-block animate-underline text-body-emphasis text-decoration-none py-2" href="/cont/comenzi/<?php echo $ord['id']; ?>">
                          <span class="animate-target"><?php echo htmlspecialchars($ord['order_number']); ?></span>
                        </a>
                        <ul class="list-unstyled fw-normal text-body m-0 d-md-none">
                          <li><?php echo date('d.m.Y', strtotime($ord['created_at'])); ?></li>
                          <li class="d-flex align-items-center">
                            <span class="bg-<?php echo $statusColors[$ord['order_status']] ?? 'secondary'; ?> rounded-circle p-1 me-2"></span>
                            <?php echo $statusLabels[$ord['order_status']] ?? $ord['order_status']; ?>
                          </li>
                          <li class="fw-medium text-body-emphasis"><?php echo number_format($ord['total'], 2); ?> RON</li>
                        </ul>
                      </td>
                      <td class="fw-medium py-3 d-none d-md-table-cell">
                        <?php echo date('d.m.Y', strtotime($ord['created_at'])); ?>
                      </td>
                      <td class="fw-medium py-3 d-none d-md-table-cell">
                        <span class="d-flex align-items-center">
                          <span class="bg-<?php echo $statusColors[$ord['order_status']] ?? 'secondary'; ?> rounded-circle p-1 me-2"></span>
                          <?php echo $statusLabels[$ord['order_status']] ?? $ord['order_status']; ?>
                        </span>
                      </td>
                      <td class="fw-medium py-3 d-none d-md-table-cell">
                        <?php echo number_format($ord['total'], 2); ?> RON
                      </td>
                      <td class="py-3 pe-0">
                        <span class="d-flex align-items-center justify-content-end position-relative gap-1 gap-sm-2 ms-n2 ms-sm-0">
                          <?php foreach ($ord['items'] as $item): ?>
                          <?php
                          $itemImage = $item['image'] ?? 'assets/img/shop/electronics/thumbs/01.png';
                          if (!str_starts_with($itemImage, 'http') && !str_starts_with($itemImage, '/') && !str_starts_with($itemImage, 'assets/')) {
                              $itemImage = 'assets/img/shop/electronics/thumbs/' . $itemImage;
                          }
                          ?>
                          <span><img src="<?php echo htmlspecialchars($itemImage); ?>" width="64" alt="<?php echo htmlspecialchars($item['product_name']); ?>"></span>
                          <?php endforeach; ?>
                          <?php if ($ord['items_count'] > 3): ?>
                          <span class="bg-body-secondary rounded d-flex align-items-center justify-content-center" style="width: 64px; height: 64px">
                            <span class="fs-xs text-body-secondary">+<?php echo $ord['items_count'] - 3; ?></span>
                          </span>
                          <?php endif; ?>
                          <a class="btn btn-icon btn-ghost btn-secondary stretched-link border-0" href="/cont/comenzi/<?php echo $ord['id']; ?>" aria-label="Vezi detalii comandă">
                            <i class="ci-chevron-right fs-lg"></i>
                          </a>
                        </span>
                      </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

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

