<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();
require_once __DIR__ . '/quotation_lib.php';

$pageTitle = 'Quotation Form';
$errors=[]; $success=''; $id=(int)($_GET['id'] ?? $_POST['id'] ?? 0); $isEdit=$id>0;

/* -----------------------------
   Currency helpers
   ROE direction supported:
   - CURRENCY_PER_USD: selected currency amount = USD/base amount * ROE
   - USD_PER_CURRENCY: selected currency amount = USD/base amount / ROE
----------------------------- */
function quote_currency_amount(float $amount, float $roe, string $direction): float
{
    $roe = $roe > 0 ? $roe : 1.0;
    $direction = strtoupper(trim($direction));

    if ($direction === 'USD_PER_CURRENCY') {
        return $amount / $roe;
    }

    return $amount * $roe;
}

function quote_currency_meta(PDO $pdo, string $code): array
{
    $code = strtoupper(trim($code));
    if ($code === '') {
        $code = 'USD';
    }

    try {
        $st = $pdo->prepare("
            SELECT CurrencyCode, Currency, ROE, roe_direction, roe_updated_at, roe_source
            FROM tblcurrency
            WHERE status = 1
              AND CurrencyCode = :code
            LIMIT 1
        ");
        $st->execute([':code' => $code]);
        $row = $st->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $roe = (float)($row['ROE'] ?? 1);
            if ($roe <= 0) {
                $roe = 1;
            }

            return [
                'code' => (string)($row['CurrencyCode'] ?? $code),
                'name' => (string)($row['Currency'] ?? $code),
                'roe' => $roe,
                'direction' => (string)($row['roe_direction'] ?? 'CURRENCY_PER_USD'),
                'updated_at' => (string)($row['roe_updated_at'] ?? ''),
                'source' => (string)($row['roe_source'] ?? ''),
            ];
        }
    } catch (Throwable $e) {
        // fall through to safe default
    }

    return [
        'code' => $code,
        'name' => $code,
        'roe' => 1.0,
        'direction' => 'CURRENCY_PER_USD',
        'updated_at' => '',
        'source' => '',
    ];
}


if (isset($_GET['ajax']) && $_GET['ajax']==='room_types') {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok'=>true,'rows'=>q_fetch_room_types_by_property($pdo,(int)($_GET['property_id']??0))]); exit;
}
if (isset($_GET['ajax']) && $_GET['ajax']==='agent_contacts') {
    header('Content-Type: application/json; charset=utf-8');
    $agentId=(int)($_GET['agent_id']??0); $rows=[];
    if($agentId>0){$st=$pdo->prepare('SELECT id, firstname, lastname, email, mobile, phone FROM consultants WHERE agent_id=:a ORDER BY firstname, lastname');$st->execute([':a'=>$agentId]);$rows=$st->fetchAll(PDO::FETCH_ASSOC)?:[];}
    echo json_encode(['ok'=>true,'rows'=>$rows]); exit;
}
if ($_SERVER['REQUEST_METHOD']==='POST' && (($_GET['ajax']??'')==='rate_preview')) {
    header('Content-Type: application/json; charset=utf-8');

    $roomRows=q_normalize_room_rows(is_array($_POST['room_rows']??null)?$_POST['room_rows']:[]);
    $currencyMeta = quote_currency_meta($pdo, (string)($_POST['currency'] ?? 'USD'));
    $roe = (float)$currencyMeta['roe'];
    $roeDirection = (string)$currencyMeta['direction'];

    $prices=q_build_price_rows($pdo,$roomRows,((int)($_POST['agent_id']??0)>0?(int)$_POST['agent_id']:null),(string)($_POST['check_in']??''),(string)($_POST['check_out']??''));

    $baseSubtotal=0;
    foreach($prices as $p){
        $baseSubtotal+=(float)$p['night_total'];
    }

    $subtotal = quote_currency_amount($baseSubtotal, $roe, $roeDirection);

    foreach($prices as &$p){
        $p['base_night_total'] = round((float)($p['night_total'] ?? 0), 2);
        $p['night_total'] = round(quote_currency_amount((float)($p['night_total'] ?? 0), $roe, $roeDirection), 2);
    }
    unset($p);

    $disc=q_discount_amount($subtotal,(string)($_POST['discount_type']??'none'),(float)($_POST['discount_value']??0));
    $total=max(0,$subtotal-$disc);

    $availability=[]; foreach($roomRows as $rr){ if((int)$rr['room_type_id']>0){$availability[]=array_merge(['room_type_id'=>(int)$rr['room_type_id'],'qty_rooms'=>(int)$rr['qty_rooms']], q_count_available_rooms_by_type($pdo,(int)($_POST['property_id']??0),(int)$rr['room_type_id'],(string)($_POST['check_in']??''),(string)($_POST['check_out']??'')));}}

    echo json_encode([
        'ok'=>true,
        'prices'=>$prices,
        'base_subtotal'=>round($baseSubtotal,2),
        'subtotal'=>round($subtotal,2),
        'discount_amount'=>round($disc,2),
        'total'=>round($total,2),
        'summary'=>q_summarize_room_rows($roomRows),
        'availability'=>$availability,
        'currency'=>[
            'code'=>$currencyMeta['code'],
            'name'=>$currencyMeta['name'],
            'roe'=>round($roe,5),
            'direction'=>$roeDirection,
            'updated_at'=>$currencyMeta['updated_at'],
            'source'=>$currencyMeta['source'],
        ]
    ]); exit;
}

$properties=$pdo->query('SELECT id,name,code FROM properties WHERE is_active=1 ORDER BY name')->fetchAll(PDO::FETCH_ASSOC);
$agents=$pdo->query('SELECT id,firstname,lastname FROM agents ORDER BY firstname,lastname')->fetchAll(PDO::FETCH_ASSOC);
$currencies = $pdo->query("
    SELECT CurrencyCode, Currency, ROE, roe_direction, roe_updated_at, roe_source
    FROM tblcurrency
    WHERE status = 1
    ORDER BY order_no, Currency
")->fetchAll(PDO::FETCH_ASSOC);
$nationalities=[]; try{$nationalities=$pdo->query('SELECT id,nationality FROM nationality ORDER BY nationality')->fetchAll(PDO::FETCH_ASSOC);}catch(Throwable $e){}
$occassions=[]; try{$occassions=$pdo->query('SELECT id,occassion_name FROM occassions ORDER BY occassion_name')->fetchAll(PDO::FETCH_ASSOC);}catch(Throwable $e){}

$form=[
 'id'=>0,'quote_no'=>'','property_id'=>'','guest_name'=>'','agent_id'=>'','contact_id'=>'','originating_agent'=>'','voucher_no'=>'','occassion_id'=>'','nationality_id'=>'',
 'check_in'=>date('Y-m-d'),'check_out'=>date('Y-m-d',strtotime('+1 day')),'validity_date'=>date('Y-m-d',strtotime('+14 days')),'status'=>'draft',
 'reservation_notes'=>'','internal_memo'=>'','terms'=>'This quotation is subject to availability at the time of confirmation. Rates may change until the quotation is accepted.',
 'discount_type'=>'none','discount_value'=>0,'subtotal'=>0,'discount_amount'=>0,'totalamount'=>0,'currency'=>'USD','quote_roe'=>1,'quote_roe_direction'=>'CURRENCY_PER_USD',
 'room_rows'=>[['room_type_id'=>'','qty_rooms'=>1,'adults'=>2,'children'=>0]]
];

if($isEdit && $_SERVER['REQUEST_METHOD']!=='POST'){
    $st=$pdo->prepare('SELECT q.*, CONCAT(COALESCE(g.firstname,""), " ", COALESCE(g.lastname,"")) AS guest_from_guest FROM reservation_quotes q LEFT JOIN guests g ON g.id=q.guest_id WHERE q.id=:id LIMIT 1');
    $st->execute([':id'=>$id]); $q=$st->fetch(PDO::FETCH_ASSOC);
    if($q){ foreach($form as $k=>$v){ if(array_key_exists($k,$q)) $form[$k]=$q[$k]; } if(trim((string)$form['guest_name'])==='') $form['guest_name']=trim((string)$q['guest_from_guest']);
        $rs=$pdo->prepare('SELECT room_type_id, qty_rooms, adults, children FROM reservation_quote_rooms WHERE quote_id=:id ORDER BY row_no,id'); $rs->execute([':id'=>$id]);
        $form['room_rows']=$rs->fetchAll(PDO::FETCH_ASSOC) ?: $form['room_rows'];
    }
}

$selectedCurrencyMeta = quote_currency_meta($pdo, (string)($form['currency'] ?? 'USD'));
$form['quote_roe'] = $selectedCurrencyMeta['roe'];
$form['quote_roe_direction'] = $selectedCurrencyMeta['direction'];

if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_quote'])){
    foreach(['property_id','guest_name','agent_id','contact_id','originating_agent','voucher_no','occassion_id','nationality_id','check_in','check_out','validity_date','reservation_notes','internal_memo','terms','discount_type','currency'] as $k){$form[$k]=trim((string)($_POST[$k]??''));}
    if ($isEdit) {
        // Currency is locked after saving. Preserve the stored currency on edits.
        $lockedCurrency = '';
        try {
            $stLockedCur = $pdo->prepare('SELECT currency FROM reservation_quotes WHERE id=:id LIMIT 1');
            $stLockedCur->execute([':id'=>(int)$form['id']]);
            $lockedCurrency = (string)$stLockedCur->fetchColumn();
        } catch (Throwable $e) {
            $lockedCurrency = '';
        }
        if (trim($lockedCurrency) !== '') {
            $form['currency'] = trim($lockedCurrency);
        }
    }
    $selectedCurrencyMeta = quote_currency_meta($pdo, (string)($form['currency'] ?: 'USD'));
    $form['currency'] = $selectedCurrencyMeta['code'];
    $form['quote_roe'] = $selectedCurrencyMeta['roe'];
    $form['quote_roe_direction'] = $selectedCurrencyMeta['direction'];
    $form['id']=(int)($_POST['id']??0); $form['discount_value']=(float)($_POST['discount_value']??0); $form['status']=trim((string)($_POST['status']??'draft')) ?: 'draft';
    $form['room_rows']=q_normalize_room_rows(is_array($_POST['room_rows']??null)?$_POST['room_rows']:[]);
    $sum=q_summarize_room_rows($form['room_rows']);
    if((int)$form['property_id']<=0)$errors[]='Please select a property.';
    if($form['guest_name']==='')$errors[]='Please enter guest name.';
    if(!strtotime($form['check_in']) || !strtotime($form['check_out']) || strtotime($form['check_out'])<=strtotime($form['check_in']))$errors[]='Check-out must be after check-in.';
    foreach($form['room_rows'] as $i=>$rr){ if((int)$rr['room_type_id']<=0)$errors[]='Select room type on row '.($i+1).'.'; }
    $priceRows=q_build_price_rows($pdo,$form['room_rows'],((int)$form['agent_id']>0?(int)$form['agent_id']:null),$form['check_in'],$form['check_out']);
    $baseSubtotal=0; foreach($priceRows as $p){$baseSubtotal+=(float)$p['night_total'];}

    $subtotal=quote_currency_amount($baseSubtotal,(float)$form['quote_roe'],(string)$form['quote_roe_direction']);
    foreach($priceRows as &$p){
        $p['base_night_total'] = round((float)($p['night_total'] ?? 0), 2);
        $p['night_total'] = round(quote_currency_amount((float)($p['night_total'] ?? 0),(float)$form['quote_roe'],(string)$form['quote_roe_direction']), 2);
        if (isset($p['total'])) {
            $p['base_total'] = round((float)$p['total'], 2);
            $p['total'] = round(quote_currency_amount((float)$p['total'],(float)$form['quote_roe'],(string)$form['quote_roe_direction']), 2);
        }
    }
    unset($p);

    $disc=q_discount_amount($subtotal,$form['discount_type'],(float)$form['discount_value']); $total=max(0,$subtotal-$disc);
    if(!$errors){
        try{
            $pdo->beginTransaction(); $guestId=q_find_or_create_guest($pdo,$form['guest_name']); $userId=q_current_user_id();
            if((int)$form['id']>0){
                $quoteId=(int)$form['id'];
                $st=$pdo->prepare('UPDATE reservation_quotes SET property_id=:property_id, guest_id=:guest_id, guest_name=:guest_name, agent_id=:agent_id, contact_id=:contact_id, originating_agent=:originating_agent, voucher_no=:voucher_no, occassion_id=:occassion_id, nationality_id=:nationality_id, check_in=:check_in, check_out=:check_out, adults=:adults, kids=:kids, totalrooms=:totalrooms, room_type_id=:room_type_id, subtotal=:subtotal, discount_type=:discount_type, discount_value=:discount_value, discount_amount=:discount_amount, totalamount=:totalamount, currency=:currency, validity_date=:validity_date, status=:status, reservation_notes=:reservation_notes, internal_memo=:internal_memo, terms=:terms, updated_by=:updated_by, updated_at=NOW() WHERE id=:id');
            } else {
                $quoteId=0; $form['quote_no']=q_next_quote_no($pdo);
                $st=$pdo->prepare('INSERT INTO reservation_quotes (quote_no, property_id, guest_id, guest_name, agent_id, contact_id, originating_agent, voucher_no, occassion_id, nationality_id, check_in, check_out, adults, kids, totalrooms, room_type_id, subtotal, discount_type, discount_value, discount_amount, totalamount, currency, validity_date, status, reservation_notes, internal_memo, terms, created_by, updated_by, updated_at) VALUES (:quote_no, :property_id, :guest_id, :guest_name, :agent_id, :contact_id, :originating_agent, :voucher_no, :occassion_id, :nationality_id, :check_in, :check_out, :adults, :kids, :totalrooms, :room_type_id, :subtotal, :discount_type, :discount_value, :discount_amount, :totalamount, :currency, :validity_date, :status, :reservation_notes, :internal_memo, :terms, :created_by, :updated_by, NOW())');
            }
            $params=[':property_id'=>(int)$form['property_id'],':guest_id'=>$guestId,':guest_name'=>$form['guest_name'],':agent_id'=>(int)$form['agent_id']>0?(int)$form['agent_id']:null,':contact_id'=>(int)$form['contact_id']>0?(int)$form['contact_id']:null,':originating_agent'=>(int)$form['originating_agent']>0?(int)$form['originating_agent']:null,':voucher_no'=>$form['voucher_no']?:null,':occassion_id'=>(int)$form['occassion_id']>0?(int)$form['occassion_id']:null,':nationality_id'=>(int)$form['nationality_id']>0?(int)$form['nationality_id']:null,':check_in'=>$form['check_in'],':check_out'=>$form['check_out'],':adults'=>$sum['adults'],':kids'=>$sum['kids'],':totalrooms'=>$sum['totalrooms'],':room_type_id'=>(int)($form['room_rows'][0]['room_type_id']??0),':subtotal'=>round($subtotal,2),':discount_type'=>$form['discount_type'],':discount_value'=>(float)$form['discount_value'],':discount_amount'=>$disc,':totalamount'=>round($total,2),':currency'=>$form['currency']?:'USD',':validity_date'=>$form['validity_date']?:null,':status'=>$form['status'],':reservation_notes'=>$form['reservation_notes']?:null,':internal_memo'=>$form['internal_memo']?:null,':terms'=>$form['terms']?:null,':updated_by'=>$userId>0?$userId:null];
            if((int)$form['id']>0){$params[':id']=(int)$form['id'];}else{$params[':quote_no']=$form['quote_no'];$params[':created_by']=$userId>0?$userId:null;}
            $st->execute($params); if($quoteId<=0)$quoteId=(int)$pdo->lastInsertId();
            $pdo->prepare('DELETE FROM reservation_quote_rooms WHERE quote_id=:id')->execute([':id'=>$quoteId]);
            $ins=$pdo->prepare('INSERT INTO reservation_quote_rooms (quote_id,row_no,room_type_id,qty_rooms,adults,children,check_in,check_out,line_total) VALUES (:quote_id,:row_no,:room_type_id,:qty_rooms,:adults,:children,:check_in,:check_out,0)');
            foreach($form['room_rows'] as $idx=>$rr){$ins->execute([':quote_id'=>$quoteId,':row_no'=>$idx+1,':room_type_id'=>(int)$rr['room_type_id'],':qty_rooms'=>(int)$rr['qty_rooms'],':adults'=>(int)$rr['adults'],':children'=>(int)$rr['children'],':check_in'=>$form['check_in'],':check_out'=>$form['check_out']]);}
            q_save_quote_prices($pdo,$quoteId,(int)$form['property_id'],$form['room_rows'],$priceRows);
            $pdo->commit(); header('Location: quotation_list.php'); exit;
        }catch(Throwable $e){ if($pdo->inTransaction())$pdo->rollBack(); $errors[]=$e->getMessage(); }
    }
}
if(isset($_GET['saved']))$success='Quotation saved successfully.';
$roomTypes=q_fetch_room_types_by_property($pdo,(int)$form['property_id']);
$contacts=[]; if((int)$form['agent_id']>0){$st=$pdo->prepare('SELECT id,firstname,lastname,email,mobile,phone FROM consultants WHERE agent_id=:a ORDER BY firstname,lastname');$st->execute([':a'=>(int)$form['agent_id']]);$contacts=$st->fetchAll(PDO::FETCH_ASSOC)?:[];}
require_once __DIR__ . '/../../includes/header.php';
?>
<div class="hero-band quote-hero mb-2"><div class="d-flex justify-content-between align-items-center flex-wrap gap-2"><div><div class="page-eyebrow text-white-50"><i class="bi bi-file-earmark-text"></i> Reservations</div><div class="hero-title">Quotation Form</div><div class="hero-subtitle">Flexible quote that can convert into a confirmed reservation.</div></div><div class="d-flex gap-2"><a href="quotation_list.php" class="btn btn-sm btn-outline-light">Quotes</a><?php if($isEdit): ?><a href="quotation_pdf.php?id=<?php echo (int)$form['id']; ?>" target="_blank" class="btn btn-sm btn-light">PDF Preview</a><a href="quotation_convert.php?id=<?php echo (int)$form['id']; ?>" class="btn btn-sm btn-warning">Convert</a><?php endif; ?></div></div></div>
<?php if($success): ?><div class="alert alert-success py-2"><?php echo q_h($success); ?></div><?php endif; ?><?php if($errors): ?><div class="alert alert-danger py-2"><b>Please fix:</b><ul class="mb-0"><?php foreach($errors as $e): ?><li><?php echo q_h($e); ?></li><?php endforeach; ?></ul></div><?php endif; ?>
<form method="post" id="quoteForm" class="row g-2">
<input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">
<input type="hidden" name="quote_roe" id="quote_roe" value="<?php echo q_h($form['quote_roe']); ?>">
<input type="hidden" name="quote_roe_direction" id="quote_roe_direction" value="<?php echo q_h($form['quote_roe_direction']); ?>">
<div class="col-xl-7"><div class="card panel-card"><div class="card-body p-3"><div class="row g-2">
<div class="col-md-4"><label class="form-label">Property</label><select name="property_id" id="property_id" class="form-select" required><option value="">Select</option><?php foreach($properties as $p): ?><option value="<?php echo (int)$p['id']; ?>" <?php echo (int)$form['property_id']===(int)$p['id']?'selected':''; ?>><?php echo q_h($p['name']); ?> - <?php echo q_h($p['code']); ?></option><?php endforeach; ?></select></div>
<div class="col-md-4"><label class="form-label">Guest Name</label><input name="guest_name" class="form-control" value="<?php echo q_h($form['guest_name']); ?>" required></div>
<div class="col-md-4"><label class="form-label">Agent</label><select name="agent_id" id="agent_id" class="form-select"><option value="">Select Agent</option><?php foreach($agents as $a): $n=trim(($a['firstname']??'').' '.($a['lastname']??'')); ?><option value="<?php echo (int)$a['id']; ?>" <?php echo (int)$form['agent_id']===(int)$a['id']?'selected':''; ?>><?php echo q_h($n?:('Agent #'.$a['id'])); ?></option><?php endforeach; ?></select></div>
<div class="col-md-3"><label class="form-label">Check In</label><input type="date" name="check_in" id="check_in" class="form-control" value="<?php echo q_h($form['check_in']); ?>"></div><div class="col-md-3"><label class="form-label">Check Out</label><input type="date" name="check_out" id="check_out" class="form-control" value="<?php echo q_h($form['check_out']); ?>"></div><div class="col-md-3"><label class="form-label">Valid Until</label><input type="date" name="validity_date" class="form-control" value="<?php echo q_h($form['validity_date']); ?>"></div><div class="col-md-3"><label class="form-label">Status</label><select name="status" class="form-select"><?php foreach(['draft','sent','accepted','cancelled','expired'] as $s): ?><option value="<?php echo $s; ?>" <?php echo $form['status']===$s?'selected':''; ?>><?php echo ucfirst($s); ?></option><?php endforeach; ?></select></div>
<div class="col-md-4"><label class="form-label">Contact</label><select name="contact_id" id="contact_id" class="form-select"><option value="">Select contact</option><?php foreach($contacts as $c): $cn=trim(($c['firstname']??'').' '.($c['lastname']??'')); ?><option value="<?php echo (int)$c['id']; ?>" <?php echo (int)$form['contact_id']===(int)$c['id']?'selected':''; ?>><?php echo q_h($cn); ?></option><?php endforeach; ?></select></div><div class="col-md-4"><label class="form-label">Voucher / Ref</label><input name="voucher_no" class="form-control" value="<?php echo q_h($form['voucher_no']); ?>"></div>
<div class="col-md-4">
    <label class="form-label">Currency</label>
    <?php if ($isEdit): ?>
        <input type="hidden" name="currency" value="<?php echo q_h($form['currency']); ?>">
    <?php endif; ?>
    <select name="<?php echo $isEdit ? 'currency_locked_display' : 'currency'; ?>" id="currency" class="form-select" required <?php echo $isEdit ? 'disabled' : ''; ?>>
        <option value="">Select Currency</option>
        <?php foreach ($currencies as $c): ?>
            <?php
                $roe = (float)($c['ROE'] ?? 1);
                if ($roe <= 0) $roe = 1;
                $direction = (string)($c['roe_direction'] ?? 'CURRENCY_PER_USD');
            ?>
            <option
                value="<?php echo q_h($c['CurrencyCode']); ?>"
                data-roe="<?php echo q_h($roe); ?>"
                data-direction="<?php echo q_h($direction); ?>"
                data-updated="<?php echo q_h($c['roe_updated_at'] ?? ''); ?>"
                data-source="<?php echo q_h($c['roe_source'] ?? ''); ?>"
                <?php echo $form['currency'] === $c['CurrencyCode'] ? 'selected' : ''; ?>>
                <?php echo q_h($c['CurrencyCode'] . ' - ' . $c['Currency']); ?>
            </option>
        <?php endforeach; ?>
    </select>
    <div class="currency-lock-note small mt-1" id="currencyRoeNote"></div>
</div>
<div class="col-12"><div class="d-flex justify-content-between align-items-center mt-2 mb-1"><b>Room Mix</b><button type="button" id="addRoomRowBtn" class="btn btn-sm btn-outline-primary">Add Room Type</button></div><div id="roomRowsWrap"><?php foreach($form['room_rows'] as $idx=>$rr): ?><div class="room-row border rounded-3 p-2 mb-2" data-index="<?php echo $idx; ?>"><div class="row g-2 align-items-end"><div class="col-md-5"><label class="form-label">Room Type</label><select name="room_rows[<?php echo $idx; ?>][room_type_id]" class="form-select room-type-select"><option value="">Select</option><?php foreach($roomTypes as $rt): ?><option value="<?php echo (int)$rt['id']; ?>" <?php echo (int)$rr['room_type_id']===(int)$rt['id']?'selected':''; ?>><?php echo q_h($rt['title']); ?></option><?php endforeach; ?></select></div><div class="col-md-2"><label class="form-label">Rooms</label><input type="number" min="1" name="room_rows[<?php echo $idx; ?>][qty_rooms]" class="form-control room-qty" value="<?php echo (int)$rr['qty_rooms']; ?>"></div><div class="col-md-2"><label class="form-label">Adults</label><input type="number" min="0" name="room_rows[<?php echo $idx; ?>][adults]" class="form-control room-adults" value="<?php echo (int)$rr['adults']; ?>"></div><div class="col-md-2"><label class="form-label">Children</label><input type="number" min="0" name="room_rows[<?php echo $idx; ?>][children]" class="form-control room-children" value="<?php echo (int)$rr['children']; ?>"></div><div class="col-md-1"><button type="button" class="btn btn-outline-danger remove-room-row">×</button></div></div></div><?php endforeach; ?></div></div>
<div class="col-md-4"><label class="form-label">Discount Type</label><select name="discount_type" id="discount_type" class="form-select"><option value="none">None</option><option value="amount" <?php echo $form['discount_type']==='amount'?'selected':''; ?>>Amount</option><option value="percent" <?php echo $form['discount_type']==='percent'?'selected':''; ?>>Percent</option></select></div><div class="col-md-4"><label class="form-label">Discount Value</label><input type="number" step="0.01" name="discount_value" id="discount_value" class="form-control" value="<?php echo q_h($form['discount_value']); ?>"></div>
<div class="col-12"><label class="form-label">Notes</label><textarea name="reservation_notes" rows="2" class="form-control"><?php echo q_h($form['reservation_notes']); ?></textarea></div><div class="col-12"><label class="form-label">Terms</label><textarea name="terms" rows="2" class="form-control"><?php echo q_h($form['terms']); ?></textarea></div>
</div><div class="d-flex gap-2 mt-3"><button name="save_quote" value="1" class="btn btn-primary">Save Quote</button><a href="quotation_list.php" class="btn btn-light">Back</a></div></div></div></div>
<div class="col-xl-5"><div class="card panel-card sticky-preview"><div class="card-header d-flex justify-content-between align-items-center"><b>Live Quote Preview</b><span class="badge bg-light text-dark border" id="previewCurrency"><?php echo q_h($form['currency']); ?></span></div><div class="card-body"><div class="row g-2 mb-2"><div class="col-4"><div class="mini-stat"><span>Rooms</span><strong id="sum_rooms">0</strong></div></div><div class="col-4"><div class="mini-stat"><span>Adults</span><strong id="sum_adults">0</strong></div></div><div class="col-4"><div class="mini-stat"><span>Kids</span><strong id="sum_kids">0</strong></div></div></div><div id="availabilityBox" class="small mb-2 text-muted"></div><div class="table-responsive"><table class="table table-sm"><thead><tr><th>Date</th><th class="text-end">Total</th></tr></thead><tbody id="previewRows"><tr><td colspan="2" class="text-muted">Change room mix to preview.</td></tr></tbody></table></div><div class="quote-total"><div><span>Subtotal</span><strong id="subtotalText">0.00</strong></div><div><span>Discount</span><strong id="discountText">0.00</strong></div><div class="grand"><span>Total</span><strong id="totalText">0.00</strong></div></div><div id="baseCurrencyNote" class="small text-muted mt-2"></div></div></div></div>
</form>
<style>.quote-hero{padding:12px 16px!important;border-radius:16px}.quote-hero .hero-title{font-size:1.15rem}.quote-hero .hero-subtitle{font-size:.78rem}.form-label{font-size:.76rem;font-weight:700;margin-bottom:2px}.form-control,.form-select{min-height:34px;font-size:.86rem}.sticky-preview{position:sticky;top:76px}.mini-stat{background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px;padding:8px 10px}.mini-stat span{display:block;font-size:.7rem;color:#64748b}.mini-stat strong{font-size:1rem}.quote-total{border-top:1px solid #e5e7eb;padding-top:8px}.quote-total div{display:flex;justify-content:space-between;padding:4px 0}.quote-total .grand{font-size:1.2rem;font-weight:900}.currency-lock-note{color:#64748b}.currency-locked{background:#f8fafc;color:#64748b}</style>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('quoteForm');
    const wrap = document.getElementById('roomRowsWrap');
    const property = document.getElementById('property_id');
    const agent = document.getElementById('agent_id');
    const contact = document.getElementById('contact_id');
    const addBtn = document.getElementById('addRoomRowBtn');
    const currency = document.getElementById('currency');
    const roeInput = document.getElementById('quote_roe');
    const roeDirectionInput = document.getElementById('quote_roe_direction');
    const roeNote = document.getElementById('currencyRoeNote');
    const previewCurrency = document.getElementById('previewCurrency');
    const baseCurrencyNote = document.getElementById('baseCurrencyNote');

    function money(v) {
        return Number(v || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    function selectedCurrencyCode() {
        if (!currency) return 'USD';
        return currency.value || 'USD';
    }

    function syncCurrencyMeta() {
        if (!currency) return;

        const opt = currency.options[currency.selectedIndex];
        const code = selectedCurrencyCode();
        const roe = opt ? Number(opt.dataset.roe || 1) : 1;
        const direction = opt ? (opt.dataset.direction || 'CURRENCY_PER_USD') : 'CURRENCY_PER_USD';
        const updated = opt ? (opt.dataset.updated || '') : '';
        const source = opt ? (opt.dataset.source || '') : '';

        if (roeInput) roeInput.value = roe > 0 ? roe.toFixed(5) : '1.00000';
        if (roeDirectionInput) roeDirectionInput.value = direction;

        if (previewCurrency) previewCurrency.textContent = code;

        let txt = 'ROE: ' + (roe > 0 ? roe.toFixed(5) : '1.00000') + ' · ' + direction.replaceAll('_', ' ');
        if (updated) txt += ' · Updated: ' + updated;
        if (source) txt += ' · Source: ' + source;

        if (currency.disabled) {
            txt = 'Currency locked after saving · ' + txt;
            currency.classList.add('currency-locked');
        }

        if (roeNote) roeNote.textContent = txt;
    }

    function optionHtml() {
        const f = wrap.querySelector('.room-type-select');
        return f ? f.innerHTML : '<option value="">Select</option>';
    }

    function reindex() {
        wrap.querySelectorAll('.room-row').forEach((r, i) => {
            r.dataset.index = i;
            ['room_type_id','qty_rooms','adults','children'].forEach(k => {
                let el = r.querySelector(k === 'room_type_id' ? '.room-type-select' : k === 'qty_rooms' ? '.room-qty' : k === 'adults' ? '.room-adults' : '.room-children');
                if (el) el.name = `room_rows[${i}][${k}]`;
            });
        });
        refresh();
    }

    function attach(r) {
        r.querySelectorAll('select,input').forEach(el => {
            el.addEventListener('change', refresh);
            el.addEventListener('input', refresh);
        });

        let rm = r.querySelector('.remove-room-row');
        if (rm) {
            rm.onclick = () => {
                if (wrap.querySelectorAll('.room-row').length > 1) {
                    r.remove();
                    reindex();
                }
            };
        }
    }

    wrap.querySelectorAll('.room-row').forEach(attach);

    addBtn.onclick = () => {
        let i = wrap.querySelectorAll('.room-row').length;
        let d = document.createElement('div');
        d.className = 'room-row border rounded-3 p-2 mb-2';
        d.dataset.index = i;
        d.innerHTML = `<div class="row g-2 align-items-end"><div class="col-md-5"><label class="form-label">Room Type</label><select name="room_rows[${i}][room_type_id]" class="form-select room-type-select">${optionHtml()}</select></div><div class="col-md-2"><label class="form-label">Rooms</label><input type="number" min="1" name="room_rows[${i}][qty_rooms]" class="form-control room-qty" value="1"></div><div class="col-md-2"><label class="form-label">Adults</label><input type="number" min="0" name="room_rows[${i}][adults]" class="form-control room-adults" value="1"></div><div class="col-md-2"><label class="form-label">Children</label><input type="number" min="0" name="room_rows[${i}][children]" class="form-control room-children" value="0"></div><div class="col-md-1"><button type="button" class="btn btn-outline-danger remove-room-row">×</button></div></div>`;
        wrap.appendChild(d);
        attach(d);
        refresh();
    };

    async function loadRoomTypes() {
        let resp = await fetch('quotation_form.php?ajax=room_types&property_id=' + encodeURIComponent(property.value), {credentials:'same-origin'});
        let j = await resp.json();
        let html = '<option value="">Select</option>';

        (j.rows || []).forEach(r => html += `<option value="${r.id}">${r.title}</option>`);
        wrap.querySelectorAll('.room-type-select').forEach(s => s.innerHTML = html);

        refresh();
    }

    property.addEventListener('change', loadRoomTypes);

    agent.addEventListener('change', async () => {
        let resp = await fetch('quotation_form.php?ajax=agent_contacts&agent_id=' + encodeURIComponent(agent.value), {credentials:'same-origin'});
        let j = await resp.json();

        contact.innerHTML = '<option value="">Select contact</option>';
        (j.rows || []).forEach(r => {
            let n = ((r.firstname || '') + ' ' + (r.lastname || '')).trim();
            contact.innerHTML += `<option value="${r.id}">${n}</option>`;
        });

        refresh();
    });

    if (currency) {
        currency.addEventListener('change', () => {
            syncCurrencyMeta();
            refresh();
        });
    }

    async function refresh() {
        syncCurrencyMeta();

        let fd = new FormData(form);

        /*
          Disabled select fields are not included in FormData.
          Currency is locked on edit, so force its current displayed value into AJAX preview.
        */
        if (currency && currency.disabled) {
            fd.set('currency', currency.value || '<?php echo q_h($form['currency']); ?>');
        }

        try {
            let resp = await fetch('quotation_form.php?ajax=rate_preview', {
                method: 'POST',
                body: fd,
                credentials: 'same-origin'
            });
            let j = await resp.json();
            if (!j.ok) return;

            const code = (j.currency && j.currency.code) ? j.currency.code : selectedCurrencyCode();

            document.getElementById('sum_rooms').textContent = j.summary.totalrooms || 0;
            document.getElementById('sum_adults').textContent = j.summary.adults || 0;
            document.getElementById('sum_kids').textContent = j.summary.kids || 0;

            document.getElementById('subtotalText').textContent = code + ' ' + money(j.subtotal);
            document.getElementById('discountText').textContent = code + ' ' + money(j.discount_amount);
            document.getElementById('totalText').textContent = code + ' ' + money(j.total);

            document.getElementById('previewRows').innerHTML = (j.prices || []).map(r => `
                <tr>
                    <td>${r.date}</td>
                    <td class="text-end">${code} ${money(r.night_total)}</td>
                </tr>
            `).join('') || '<tr><td colspan="2" class="text-muted">No preview.</td></tr>';

            document.getElementById('availabilityBox').innerHTML = (j.availability || []).map(a => `Type ${a.room_type_id}: need ${a.qty_rooms}, available ${a.available_rooms}`).join('<br>');

            if (baseCurrencyNote) {
                const roe = j.currency ? Number(j.currency.roe || 1) : 1;
                const direction = j.currency ? (j.currency.direction || 'CURRENCY_PER_USD') : 'CURRENCY_PER_USD';
                baseCurrencyNote.textContent = 'Preview converted using ROE ' + money(roe) + ' (' + direction.replaceAll('_', ' ') + '). Base subtotal before conversion: USD ' + money(j.base_subtotal);
            }
        } catch (e) {
            // Keep UI stable if preview fails while user is typing.
        }
    }

    form.querySelectorAll('input,select,textarea').forEach(el => {
        el.addEventListener('change', refresh);
        el.addEventListener('input', refresh);
    });

    syncCurrencyMeta();
    refresh();
});
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
