<?php
require_once __DIR__ . '/config/database.php';
$settings = getAllSettings($pdo);
requireLogin();
if (isAdmin())    redirect(BASE_URL . '/admin/index.php');
if (isInvestor()) redirect(BASE_URL . '/investor-dashboard.php');

$userId = $_SESSION['user_id'];
$tab    = $_GET['tab'] ?? 'orders';
$msg    = '';

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch();

// ── Change password ──
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['change_password'])) {
    $old=$_POST['old_password']??''; $new=$_POST['new_password']??''; $conf=$_POST['confirm_password']??'';
    if (!password_verify($old,$user['password']))
        $msg='<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> পুরনো পাসওয়ার্ড সঠিক নয়।</div>';
    elseif(strlen($new)<6)
        $msg='<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> পাসওয়ার্ড কমপক্ষে ৬ অক্ষর।</div>';
    elseif($new!==$conf)
        $msg='<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> পাসওয়ার্ড মিলছে না।</div>';
    else {
        $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($new,PASSWORD_DEFAULT),$userId]);
        $msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> পাসওয়ার্ড পরিবর্তন সফল।</div>';
    }
    $tab='password';
}

// ── Update profile ──
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['update_profile'])) {
    $name=trim($_POST['name']??''); $addr=trim($_POST['address']??''); $email=trim($_POST['email']??'');
    if(!$name) { $msg='<div class="alert alert-error">নাম আবশ্যক।</div>'; }
    else {
        $pdo->prepare("UPDATE users SET name=?,address=?,email=? WHERE id=?")->execute([$name,$addr,$email,$userId]);
        $_SESSION['user_name']=$name; $_SESSION['user_address']=$addr;
        $user['name']=$name; $user['address']=$addr; $user['email']=$email;
        $msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> প্রোফাইল আপডেট হয়েছে।</div>';
    }
    $tab='profile';
}

// ── Submit review ──
$reviewEnabled=($settings['review_enabled']??'1')==='1';
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['submit_review']) && $reviewEnabled){
    $rpid=(int)($_POST['review_product_id']??0);
    $rating=min(5,max(1,(int)($_POST['rating']??5)));
    $comment=trim($_POST['comment']??'');
    if($rpid && $comment){
        $chk=$pdo->prepare("SELECT id FROM reviews WHERE user_id=? AND product_id=?");
        $chk->execute([$userId,$rpid]);
        if(!$chk->fetch()){
            $pdo->prepare("INSERT INTO reviews (product_id,user_id,rating,comment,status) VALUES(?,?,?,?,'pending')")
                ->execute([$rpid,$userId,$rating,$comment]);
            $msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> রিভিউ জমা হয়েছে। অনুমোদনের পরে প্রকাশিত হবে।</div>';
        } else {
            $msg='<div class="alert alert-warning">আপনি এই পণ্যে ইতিমধ্যে রিভিউ দিয়েছেন।</div>';
        }
    } else { $msg='<div class="alert alert-error">রেটিং ও মন্তব্য আবশ্যক।</div>'; }
    $tab='reviews';
}

$orderStmt=$pdo->prepare("SELECT * FROM orders WHERE user_id=? ORDER BY created_at DESC");
$orderStmt->execute([$userId]);
$orders=$orderStmt->fetchAll();

$navItems=[
    ['tab'=>'orders',   'icon'=>'fa-box',          'label'=>'আমার অর্ডার'],
    ['tab'=>'profile',  'icon'=>'fa-user-edit',     'label'=>'প্রোফাইল'],
    ['tab'=>'password', 'icon'=>'fa-lock',          'label'=>'পাসওয়ার্ড'],
];
if($reviewEnabled) $navItems[]=['tab'=>'reviews','icon'=>'fa-star','label'=>'রিভিউ'];

include __DIR__.'/includes/header.php';
?>

<style>
/* ── User/Investor Dashboard Layout ─── */
.dash-page{padding:24px 0 56px}
.dash-grid{display:grid;grid-template-columns:1fr;gap:20px}
@media(min-width:820px){.dash-grid{grid-template-columns:220px 1fr;gap:24px}}

/* ── Mobile tab bar ── */
.dash-tabbar{
  display:flex;overflow-x:auto;gap:0;
  background:var(--navy);border-radius:var(--r-lg);
  scrollbar-width:none;
}
.dash-tabbar::-webkit-scrollbar{display:none}
.dash-tab{
  display:flex;flex-direction:column;align-items:center;gap:4px;
  padding:12px 14px;color:rgba(255,255,255,.6);
  font-size:.75rem;font-weight:500;cursor:pointer;
  border-bottom:3px solid transparent;white-space:nowrap;
  transition:all .2s;flex:1;min-width:72px;text-decoration:none;
}
.dash-tab:hover,.dash-tab.active{color:var(--gold);border-bottom-color:var(--gold);background:rgba(212,175,55,.07)}
.dash-tab i{font-size:1.1rem}
@media(min-width:820px){.dash-tabbar{display:none}} /* hidden on desktop */

/* ── Desktop sidebar ── */
.dash-sidebar{
  background:var(--navy);border-radius:var(--r-lg);
  display:none;position:sticky;top:80px;height:fit-content;
}
@media(min-width:820px){.dash-sidebar{display:block}}
.ds-user{padding:20px 18px 16px;border-bottom:1px solid rgba(255,255,255,.1);margin-bottom:4px}
.ds-avatar{width:52px;height:52px;background:var(--gold);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.3rem;color:var(--navy);font-weight:700;margin-bottom:8px}
.ds-name{color:#fff;font-weight:700;font-size:.93rem}
.ds-role{color:rgba(255,255,255,.45);font-size:.78rem}
.ds-nav a{
  display:flex;align-items:center;gap:10px;
  padding:11px 18px;color:rgba(255,255,255,.68);
  font-size:.88rem;font-weight:500;
  transition:all .2s;border-left:3px solid transparent;
}
.ds-nav a:hover,.ds-nav a.active{color:var(--gold);background:rgba(212,175,55,.08);border-left-color:var(--gold)}
.ds-nav a i{width:16px;text-align:center}
.ds-nav .logout-link{color:#e53e3e!important}

/* ── Content cards ── */
.dash-content-card{background:#fff;border-radius:var(--r-lg);padding:18px;box-shadow:var(--sh);margin-bottom:18px}
@media(min-width:600px){.dash-content-card{padding:24px}}
.dash-content-card h3{font-size:1.05rem;font-weight:700;color:var(--navy);margin-bottom:16px;padding-bottom:10px;border-bottom:2px solid var(--g100)}

/* ── Star widget ── */
.star-widget{display:flex;gap:5px;cursor:pointer}
.star-widget .sw-star{font-size:1.9rem;color:#e8e6e1;transition:color .13s,transform .11s;line-height:1;user-select:none}
.star-widget .sw-star.lit{color:#D4AF37}
.star-widget .sw-star:hover{transform:scale(1.2)}
</style>

<div class="dash-page">
<div class="container">

    <!-- ── Mobile Tab Bar ── -->
    <div class="dash-tabbar" style="margin-bottom:18px;">
        <?php foreach($navItems as $ni): ?>
        <a href="?tab=<?=$ni['tab']?>" class="dash-tab <?=$tab===$ni['tab']?'active':''?>">
            <i class="fas <?=$ni['icon']?>"></i>
            <?=$ni['label']?>
        </a>
        <?php endforeach; ?>
        <a href="<?=BASE_URL?>/logout.php" class="dash-tab" style="color:#e88;min-width:72px;">
            <i class="fas fa-sign-out-alt"></i>লগআউট
        </a>
    </div>

    <div class="dash-grid">

        <!-- ── Desktop Sidebar ── -->
        <div class="dash-sidebar">
            <div class="ds-user">
                <div class="ds-avatar"><?=mb_substr($user['name'],0,1)?></div>
                <div class="ds-name"><?=e($user['name'])?></div>
                <div class="ds-role">গ্রাহক</div>
            </div>
            <nav class="ds-nav">
                <?php foreach($navItems as $ni): ?>
                <a href="?tab=<?=$ni['tab']?>" class="<?=$tab===$ni['tab']?'active':''?>">
                    <i class="fas <?=$ni['icon']?>"></i><?=$ni['label']?>
                </a>
                <?php endforeach; ?>
                <a href="<?=BASE_URL?>/logout.php" class="logout-link"><i class="fas fa-sign-out-alt"></i>লগআউট</a>
            </nav>
        </div>

        <!-- ── Content ── -->
        <div>
            <?=$msg?>

            <?php if($tab==='orders'): ?>
            <div class="dash-content-card">
                <h3>আমার অর্ডারসমূহ</h3>
                <?php if(empty($orders)): ?>
                    <div style="text-align:center;padding:36px 0;color:var(--g400);">
                        <i class="fas fa-box-open" style="font-size:2.8rem;display:block;margin-bottom:12px;"></i>
                        <p style="margin-bottom:16px;">কোনো অর্ডার নেই।</p>
                        <a href="<?=BASE_URL?>/index.php" class="btn-primary" style="display:inline-block;width:auto;padding:10px 24px;">শপিং করুন</a>
                    </div>
                <?php else: ?>
                    <div style="overflow-x:auto;">
                        <table style="min-width:420px;">
                            <thead><tr>
                                <th>অর্ডার নং</th><th>তারিখ</th><th>মোট</th><th>স্ট্যাটাস</th>
                            </tr></thead>
                            <tbody>
                            <?php foreach($orders as $o): ?>
                            <tr>
                                <td><strong>#<?=str_pad($o['id'],6,'0',STR_PAD_LEFT)?></strong></td>
                                <td><?=date('d/m/Y',strtotime($o['created_at']))?></td>
                                <td>৳<?=number_format($o['total_amount'],2)?></td>
                                <td><span class="status-badge status-<?=$o['status']?>">
                                    <?=match($o['status']){'pending'=>'অপেক্ষমান','processing'=>'প্রক্রিয়াধীন','shipped'=>'পাঠানো হয়েছে','delivered'=>'ডেলিভারি হয়েছে','cancelled'=>'বাতিল',default=>$o['status']}?>
                                </span></td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <?php elseif($tab==='profile'): ?>
            <div class="dash-content-card">
                <h3>প্রোফাইল সম্পাদনা</h3>
                <form method="POST">
                    <div class="form-group">
                        <label class="form-label">পূর্ণ নাম *</label>
                        <input type="text" class="form-control" name="name" value="<?=e($user['name'])?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">মোবাইল নম্বর (পরিবর্তনযোগ্য নয়)</label>
                        <input type="text" class="form-control" value="<?=e($user['phone'])?>" readonly style="background:var(--g100);cursor:not-allowed;">
                    </div>
                    <div class="form-group">
                        <label class="form-label">ইমেইল</label>
                        <input type="email" class="form-control" name="email" value="<?=e($user['email']??'')?>">
                    </div>
                    <div class="form-group">
                        <label class="form-label">ঠিকানা</label>
                        <textarea class="form-control" name="address" rows="3"><?=e($user['address']??'')?></textarea>
                    </div>
                    <button type="submit" name="update_profile" class="btn-primary" style="width:auto;padding:10px 28px;">আপডেট করুন</button>
                </form>
            </div>

            <?php elseif($tab==='password'): ?>
            <div class="dash-content-card">
                <h3>পাসওয়ার্ড পরিবর্তন</h3>
                <form method="POST">
                    <div class="form-group">
                        <label class="form-label">পুরনো পাসওয়ার্ড *</label>
                        <input type="password" class="form-control" name="old_password" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">নতুন পাসওয়ার্ড *</label>
                        <input type="password" class="form-control" name="new_password" placeholder="কমপক্ষে ৬ অক্ষর" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">পাসওয়ার্ড নিশ্চিত করুন *</label>
                        <input type="password" class="form-control" name="confirm_password" required>
                    </div>
                    <button type="submit" name="change_password" class="btn-primary" style="width:auto;padding:10px 28px;">পরিবর্তন করুন</button>
                </form>
            </div>

            <?php elseif($tab==='reviews' && $reviewEnabled): ?>
            <div class="dash-content-card">
                <h3>রিভিউ লিখুন</h3>
                <?php
                $revItems=$pdo->prepare(
                    "SELECT DISTINCT oi.product_id, p.name, p.image
                     FROM order_items oi
                     JOIN orders o ON oi.order_id=o.id
                     JOIN products p ON oi.product_id=p.id
                     WHERE o.user_id=? AND o.status='delivered'
                     AND oi.product_id NOT IN (SELECT product_id FROM reviews WHERE user_id=?)"
                );
                $revItems->execute([$userId,$userId]);
                $reviewableProducts=$revItems->fetchAll();
                ?>
                <?php if(empty($reviewableProducts)): ?>
                    <div style="text-align:center;padding:36px 0;color:var(--g400);">
                        <i class="fas fa-star" style="font-size:2.5rem;display:block;margin-bottom:10px;"></i>
                        <p>রিভিউ দেওয়ার মতো পণ্য নেই।<br>ডেলিভারি প্রাপ্ত পণ্যে রিভিউ দিতে পারবেন।</p>
                    </div>
                <?php else: ?>
                    <?php foreach($reviewableProducts as $rp): ?>
                    <div style="border:1px solid var(--g200);border-radius:var(--r);padding:16px;margin-bottom:16px;">
                        <div style="display:flex;align-items:center;gap:10px;margin-bottom:12px;">
                            <?php if($rp['image']): ?>
                                <img src="<?=UPLOADS_URL.e($rp['image'])?>" style="width:48px;height:48px;object-fit:cover;border-radius:6px;flex-shrink:0;">
                            <?php endif; ?>
                            <strong style="color:var(--navy);"><?=e($rp['name'])?></strong>
                        </div>
                        <form method="POST">
                            <input type="hidden" name="review_product_id" value="<?=$rp['product_id']?>">
                            <div class="form-group">
                                <label class="form-label">রেটিং *</label>
                                <div class="star-widget">
                                    <?php for($s=1;$s<=5;$s++): ?>
                                        <span class="sw-star lit" data-val="<?=$s?>">★</span>
                                    <?php endfor; ?>
                                </div>
                                <input type="hidden" name="rating" class="star-input" value="5">
                            </div>
                            <div class="form-group">
                                <label class="form-label">মন্তব্য *</label>
                                <textarea class="form-control" name="comment" rows="3" placeholder="পণ্যটি সম্পর্কে আপনার মতামত লিখুন..."></textarea>
                            </div>
                            <button type="submit" name="submit_review" class="btn-sm btn-sm-navy" style="padding:9px 20px;font-size:.9rem;">
                                <i class="fas fa-paper-plane"></i> জমা দিন
                            </button>
                        </form>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <?php endif; ?>

        </div><!-- /content -->
    </div><!-- /dash-grid -->
</div><!-- /container -->
</div><!-- /dash-page -->

<script>
// ⭐ Star Rating
document.querySelectorAll('.star-widget').forEach(widget=>{
    const stars=widget.querySelectorAll('.sw-star');
    const hidden=widget.nextElementSibling;
    let sel=5;
    const paint=n=>stars.forEach((s,i)=>{
        s.classList.toggle('lit',i<n);
        s.style.color=i<n?'#D4AF37':'#e8e6e1';
    });
    stars.forEach((star,idx)=>{
        star.addEventListener('click',()=>{sel=idx+1;if(hidden)hidden.value=sel;paint(sel);});
        star.addEventListener('mouseenter',()=>paint(idx+1));
    });
    widget.addEventListener('mouseleave',()=>paint(sel));
    paint(sel);
});
</script>

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