<?php 
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'error.log');

include('include/auth.php');

$car         = $_GET['car'] ?? null;
$datechanged = $_GET['d'] ?? null;
$vehchanged  = $_GET['v'] ?? null;
$pagerole    = "user";

include('include/head.php');

if (isset($_GET['id']) && $_GET['id'] !== '0') {
    $fid = $_GET['id'];
    $sql = $db2->query("SELECT * FROM jostj_vikrentcar_orders WHERE jostj_vikrentcar_orders.id='$fid' ") or die($db2->error);
    $row = mysqli_fetch_array($sql);
} else {
    $fid2 = $_GET['webid'] ?? '';
    $sql  = $db2->query("SELECT * FROM jostj_vikrentcar_orders WHERE jostj_vikrentcar_orders.webid='$fid2' ") or die($db2->error);
    $row  = mysqli_fetch_array($sql);
    $fid  = $row['id'];
}

$idcar         = (int)$row["idcar"];
$idplace       = (int)$row["idplace"];
$idreturnplace = (int)$row["idreturnplace"];

$ritiro_ts   = (int)$row['ritiro'];
$consegna_ts = (int)$row['consegna'];
$days        = max(1, (int)$row['days']);

$order_total = (float)$row['order_total'];
$extracosts  = (float)($row['extracosts'] ?? 0.0);
$hour        = abs($consegna_ts - $ritiro_ts) / 3600;

$disfunct = "disabled";

/* time strings (append "*" to the formatted strings, not to timestamps) */
if ((int)$row['employee'] === 10) {
    $picktime_ts = strtotime('+2 hours', $ritiro_ts);
    $droptime_ts = strtotime('+2 hours', $consegna_ts);

    $picktime = date('d/m/Y H:i', $picktime_ts) . "*";
    $droptime = date('d/m/Y H:i', $droptime_ts) . "*";

    $pickdet  = "*Time Auto Adjusted. Original time was: " . date('H:i', $ritiro_ts);
    $dropdet  = "*Time Auto Adjusted. Original time was: " . date('H:i', $consegna_ts);
} else {
    $picktime = date('d-m-Y H:i', $ritiro_ts);
    $droptime = date('d-m-Y H:i', $consegna_ts);
}

/* amounts */
if (is_null($row['totpaid']) || (float)$row['totpaid'] == 0.00) {
    $resttopay = $order_total;
} else {
    if (is_null($row['cust_cost']) || (float)$row['cust_cost'] == 0.00) {
        $resttopay = $order_total - (float)$row['totpaid'];
    } else {
        $resttopay = (float)$row['cust_cost'];
    }
}
$subtotal = ($order_total + $extracosts) / 1.24;
$vat      = $order_total - $subtotal;

/* vehicle + categories */
$sql2  = $db2->query("SELECT * FROM jostj_vikrentcar_cars WHERE jostj_vikrentcar_cars.id=$idcar ") or die($db2->error);
$row2  = mysqli_fetch_array($sql2); 

$sqlcar2 = $db->query("SELECT * FROM jos8r_vikrentcar_cars WHERE jos8r_vikrentcar_cars.id='$idcar'") or die($db->error);
$rowcar2 = mysqli_fetch_array($sqlcar2);

$idcat2   = explode(';', (string)($rowcar2['idcat'] ?? ''));
$vehtype2 = $idcat2[0] ?? '';
$carcat2  = $idcat2[1] ?? '';

$sqlveh2 = $db->query("SELECT * FROM jos8r_vikrentcar_categories WHERE jos8r_vikrentcar_categories.id='$vehtype2'") or die($db->error);
$rowveh2 = mysqli_fetch_array($sqlveh2);

$sqlcar3 = $db->query("SELECT * FROM jos8r_vikrentcar_categories WHERE jos8r_vikrentcar_categories.id='$carcat2'") or die($db->error);
$rowcar3 = mysqli_fetch_array($sqlcar3);

$group2 = ($rowveh2['name'] ?? '') . " / " . ($rowcar3['name'] ?? '');

/* places */
$sql3 = $db2->query("SELECT * FROM jostj_vikrentcar_places LEFT JOIN jostj_vikrentcar_stations ON jostj_vikrentcar_places.station=jostj_vikrentcar_stations.station_id WHERE jostj_vikrentcar_places.id=$idplace ");
$row3 = mysqli_fetch_array($sql3); 
       
$sql4 = $db2->query("SELECT * FROM jostj_vikrentcar_places LEFT JOIN jostj_vikrentcar_stations ON jostj_vikrentcar_places.station=jostj_vikrentcar_stations.station_id WHERE jostj_vikrentcar_places.id=$idreturnplace ") or die($db2->error);
$row4 = mysqli_fetch_array($sql4);
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title>WV Admin - Reservation Print</title>

  <link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.css" />
  <link rel="stylesheet" href="css/invoice-print.css" />

  <style>
  /* ==== PRINT PAGE & FIT TO ONE PAGE ==== */
  @page { size: A4; margin: 12mm; }
  @media print {
    html, body { height: auto; }
    body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    .invoice, .no-break, table, .table { page-break-inside: avoid; }
  }

  /* overall compacting */
  body { font-size: 12px; }
  .invoice header .row { margin-bottom: 6mm; }
  h2.h2 { font-size: 20px; margin: 0 0 4px; }
  h4.h4 { font-size: 16px; margin: 0; }
  .bill-info address h4 { font-size: 15px; margin: 0 0 4px; }
  .bill-info address, .bill-to p { margin-bottom: 6px; }

  /* ==== GRID LAYOUT FOR SIDE LABELS ==== */
  .bill-info .row {
    display: grid;
    grid-template-columns: 60px 1fr 1fr;  /* left side label, two content columns */
    gap: 12px;
    align-items: start;
    margin-bottom: 8mm;
  }

  .side-label {
    writing-mode: vertical-rl;
    text-orientation: mixed;
    transform: rotate(180deg);
    line-height: 1;
    font-weight: 600;
    letter-spacing: 0.5px;
    color: #333;
    white-space: nowrap;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100%;
    padding: 6px 0;
    border-right: 1px solid #e0e0e0;
  }

  /* tables */
  .table.invoice-items { margin-top: 6mm; }
  .table.invoice-items th,
  .table.invoice-items td { padding: 6px 8px !important; vertical-align: middle; }
  .invoice-summary table td { padding: 6px 8px !important; }

  /* status colors (keep your mappings) */
  .statuscl { color: green; }
  .statuscl.cancelled { color: red; }
  .statuscl.standby { color: orange; }

  .noshow { display:none; }

  /* subtle divider */
  hr { margin: 6px 0; }
  </style>
</head>

<body>
<div class="invoice">
  <header class="clearfix">
    <div class="row">
      <div class="col-sm-6 mt-3">
        <h2 class="h2 mt-0 mb-1 text-dark font-weight-bold">Reservation Voucher</h2>
        <h4 class="h4 m-0 text-dark font-weight-bold">
          #<?php echo (int)$row['id']; ?>
          <?php if ((int)$row['source']==16) { echo " / Web ID: ".htmlspecialchars($row['webid']); } ?>
        </h4>
      </div>
      <div class="col-sm-6 text-right mt-3 mb-3">
        <address class="ib mr-5">
          MotorClub<br/>
          1, 18 Agglon sq, Heraklion - Crete, Greece<br/>
          Phone: +30 2810 222 408<br/>
          info@motorclub.gr
        </address>
        <div class="ib">
          <img src="https://motorclub.gr/public/assets/img/motorclub-logo-dark.png" alt="MotorClub" />
        </div>
      </div>
    </div>
  </header>

  <h2 style="text-align:center;">
    Reservation Status:
    <span class="statuscl" style="text-transform: capitalize;"><?php echo htmlspecialchars($row['status']);?></span>
  </h2>
  <p style="text-align:center;">Booked on: <?php echo date('d/m/Y H:i', (int)$row['ts']);?></p>

  <!-- Pick Up / Drop Off -->
  <div class="bill-info no-break">
    <div class="row">
      <div class="side-label">Pick Up / Drop Off</div>

      <div class="bill-to">
        <p class="h5 mb-1 text-dark font-weight-semibold">Pick Up Details:</p>
        <address>
          <h4><?php echo $picktime; ?><br/><?php echo htmlspecialchars($row3['name'] ?? ''); ?></h4>
          <hr>
          Responsible Station: <u><?php echo htmlspecialchars($row3['station_name'] ?? ''); ?></u><br/>
          Oppening Hours: <?php echo htmlspecialchars($row3['station_hours'] ?? ''); ?><br/>
          Contact Phone: <?php echo htmlspecialchars($row3['station_phone'] ?? ''); ?><br/>
          Contact Email: <?php echo htmlspecialchars($row3['station_email'] ?? ''); ?><br/>
          Pick Up Info: <?php echo htmlspecialchars($row3['station_pick_info'] ?? ''); ?>
        </address>
      </div>

      <div class="bill-to">
        <p class="h5 mb-1 text-dark font-weight-semibold">Drop Off Details:</p>
        <address>
          <h4><?php echo $droptime; ?><br/><?php echo htmlspecialchars($row4['name'] ?? ''); ?></h4>
          <hr>
          Responsible Station: <u><?php echo htmlspecialchars($row4['station_name'] ?? ''); ?></u><br/>
          Oppening Hours: <?php echo htmlspecialchars($row4['station_hours'] ?? ''); ?><br/>
          Contact Phone: <?php echo htmlspecialchars($row4['station_phone'] ?? ''); ?><br/>
          Contact Email: <?php echo htmlspecialchars($row4['station_email'] ?? ''); ?><br/>
          Pick Up Info: <?php echo htmlspecialchars($row4['station_pick_info'] ?? ''); ?>
        </address>
      </div>
    </div>
  </div>

  <!-- Vehicle -->
  <div class="bill-info no-break">
    <div class="row">
      <div class="side-label">Vehicle</div>

      <div class="bill-to">
        <p class="h5 mb-1 text-dark font-weight-semibold">Selected Vehicle Group:</p>
        <address>
          <h4><?php echo htmlspecialchars($row2['name'] ?? ''); ?> or similar</h4>
          <hr>
          <p>Optional Extras:
          <?php
            if (is_null($row['optionals']) || $row['optionals'] === '') {
              echo " None Selected";
            } else {
              $st2 = explode(';', (string)$row['optionals']);
              foreach ($st2 as $index => $value) {
                if ($value === '' || $value === null) break;

                list($optionalname, $qtyRaw) = array_pad(explode(':', $value, 2), 2, 0);
                $optionalname  = trim($optionalname);
                $optionalquant = (int)trim((string)$qtyRaw);

                if ($optionalname === '' || $optionalquant <= 0) continue;

                $sqlopt = $db2->query("SELECT * FROM jostj_vikrentcar_optionals WHERE jostj_vikrentcar_optionals.id='$optionalname'") or die($db2->error);
                $rowopt = mysqli_fetch_array($sqlopt);

                if ((int)$row['source'] == 16) {
                  $sqlopt2 = $db->query("SELECT * FROM jos8r_vikrentcar_optionals WHERE jos8r_vikrentcar_optionals.id='$optionalname'") or die($db->error);
                  $rowopt2 = mysqli_fetch_array($sqlopt2);
                  $cost = (float)str_replace([',','€','$'], '', (string)($rowopt2['cost'] ?? 0));
                } else {
                  $cost = (float)str_replace([',','€','$'], '', (string)($rowopt['cost'] ?? 0));
                }

                $optionalvalue = $cost * $optionalquant;
                ?>
                <span class="text-dark"><?php echo htmlspecialchars($rowopt['name'] ?? ('Optional '.$optionalname)); ?> X<?php echo $optionalquant; ?>, </span>
                <?php
              }
            }
          ?>
          </p>
        </address>
      </div>

      <div class="bill-to">
        <p class="h5 mb-1 text-dark font-weight-semibold">Rental Details:</p>
        <address>
        <?php if ((int)$row['employee']==10){ 
            $apsoure = (int)$row['source'];
            $sqlac = $db2->query("SELECT * FROM api_fleet WHERE api_fleet.api_fleet_partner='$apsoure' AND api_fleet.api_fleet_idcar='$idcar' ") or die($db2->error);
            $rowac = mysqli_fetch_array($sqlac);
            ?>
            <h4>Reserved ACRISS: <?php echo htmlspecialchars($rowac['api_fleet_acriss'] ?? ''); ?></h4>
        <?php } 
          if ((int)$row['source']==16){ 
            $webid  = (int)$row['webid'];
            $sqtar  = $db->query("SELECT * FROM jos8r_vikrentcar_orders LEFT JOIN jos8r_vikrentcar_dispcost ON jos8r_vikrentcar_dispcost.id=jos8r_vikrentcar_orders.idtar  WHERE jos8r_vikrentcar_orders.id='$webid'  ") or die($db->error);
            $rowtar = mysqli_fetch_array($sqtar);

            $priceid = (int)($rowtar['idprice'] ?? 0);
            $sqtar2  = $db->query("SELECT * FROM jos8r_vikrentcar_prices  WHERE jos8r_vikrentcar_prices.id='$priceid'  ") or die($db->error);
            $rowtar2 = mysqli_fetch_array($sqtar2);

            $sqlcar  = $db->query("SELECT * FROM jos8r_vikrentcar_cars WHERE jos8r_vikrentcar_cars.id='$idcar'  ") or die($db->error);
            $rowcar  = mysqli_fetch_array($sqlcar);

            $idcat   = explode(';', (string)($rowcar['idcat'] ?? ''));
            $vehtype = $idcat[0] ?? '';
            $carcat  = $idcat[1] ?? '';

            $sqlveh  = $db->query("SELECT * FROM jos8r_vikrentcar_categories WHERE jos8r_vikrentcar_categories.id='$vehtype'  ") or die($db->error);
            $rowveh  = mysqli_fetch_array($sqlveh);

            $sqlcar2 = $db->query("SELECT * FROM jos8r_vikrentcar_categories WHERE jos8r_vikrentcar_categories.id='$carcat'  ") or die($db->error);
            $rowcar2 = mysqli_fetch_array($sqlcar2);

            $group   = ($rowveh['name'] ?? '') . " / " . ($rowcar2['name'] ?? '');
            ?>
            <h4>Reserved Group: <?php echo htmlspecialchars($group); ?></h4>
            Tarrif: <?php echo htmlspecialchars($rowtar2['name'] ?? ''); ?><br/>
            Excess: <?php echo htmlspecialchars($rowtar['attrdata'] ?? ''); ?>
        <?php } else { 
            if ((int)$row['source']!=16 && (int)$row['employee']!=10){ ?>
              <h4>Reserved Group: <?php echo htmlspecialchars($group2);?></h4>
            <?php } ?>
            Excess: <?php echo htmlspecialchars($row['idtar']);?>
        <?php } ?>
        </address>
      </div>
    </div>
  </div>

  <!-- Customer -->
  <div class="bill-info no-break">
    <div class="row">
      <div class="side-label">Customer</div>

      <div class="bill-to">
        <p class="h5 mb-1 text-dark font-weight-semibold">Customer Details:</p>
        <address>
          <h4>Name: <?php echo htmlspecialchars($row['nominative']); ?></h4>
          <hr>
          Phone: <?php echo htmlspecialchars($row['phone']); ?><br/>
          Email: <?php echo htmlspecialchars($row['custmail']); ?>
        </address>
      </div>

      <div class="bill-to">
        <p class="h5 mb-1 text-dark font-weight-semibold">Customer Data:</p>
        <address><?php echo nl2br(htmlspecialchars($row['custdata'])); ?></address>
      </div>
    </div>
  </div>

  <!-- Items -->
  <table class="table table-responsive-md invoice-items">
    <thead>
      <tr class="text-dark">
        <th class="font-weight-semibold">Item</th>
        <th class="text-center font-weight-semibold">Price per Day</th>
        <th class="text-center font-weight-semibold">Days</th>
        <th class="text-center font-weight-semibold">Total</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="font-weight-semibold text-dark"><?php echo htmlspecialchars($row2['name'] ?? ''); ?> or similar</td>
        <td class="text-center"><?php echo number_format(($order_total - $extracosts)/$days, 2, '.', '') ;  ?>€</td>
        <td class="text-center"><?php echo $days; ?></td>
        <td class="text-center"><?php echo number_format(($order_total - $extracosts), 2, '.', ''); ?> €</td>
      </tr>
      <?php if($extracosts > 0){ ?>
      <tr>
        <td class="font-weight-semibold text-dark">Optional Extras</td>
        <td class="text-center"><?php echo number_format($extracosts/$days, 2, '.', '') ; ?>€</td>
        <td class="text-center"><?php echo $days; ?></td>
        <td class="text-center"><?php echo number_format($extracosts, 2, '.', ''); ?> €</td>
      </tr>
      <?php } ?>
    </tbody>
  </table>

  <!-- Summary -->
  <div class="invoice-summary">
    <div class="row justify-content-end">
      <div class="col-sm-5">
        <table class="table h6 text-dark">
          <tbody>
            <tr class="b-top-0">
              <td colspan="2">SubTotal</td>
              <td class="text-left"><?php echo number_format($subtotal, 2, '.', ''); ?> €</td>
            </tr>
            <tr>
              <td colspan="2">VAT 24% (inclusive)</td>
              <td class="text-left">(<?php echo number_format($vat, 2, '.', ''); ?> €)</td>
            </tr>
            <tr class="h5">
              <td colspan="2">Grand Total</td>
              <td class="text-left"><?php echo number_format($order_total, 2, '.', ''); ?> €</td>
            </tr>
            <tr>
              <td colspan="2">Deposit Paid</td>
              <td class="text-left">-<?php echo number_format((float)$row['totpaid'], 2, '.', ''); ?> €</td>
            </tr>
            <tr>
              <td colspan="2">Rest on Pick Up</td>
              <td class="text-left"><?php echo number_format($resttopay, 2, '.', ''); ?> €</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Notes -->
  <div class="row">
    <div class="col-sm-10 justify-content-center">
      <p><strong>Notes: </strong><?php echo htmlspecialchars($row4['station_notes'] ?? ''); ?></p>
    </div>
  </div>
</div>

<script>window.print();</script>
</body>
</html>
<?php include('include/footer.php'); ?>
