<?php
/**
 * Account Info Page
 * Converted from account-info.html
 * User profile management page
 */

$pageTitle = 'Cartzilla | Cont - Informații Personale';
$pageDescription = 'Cartzilla - Magazin Online E-Commerce';

// Initialize classes BEFORE header to allow redirects
require_once __DIR__ . '/includes/init.php';
$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';

// Handle form submissions
$successMessage = '';
$errorMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'update_basic_info':
                $updateData = [
                    'first_name' => $_POST['first_name'] ?? '',
                    'last_name' => $_POST['last_name'] ?? '',
                    'phone' => $_POST['phone'] ?? '',
                    'cnp' => $_POST['cnp'] ?? ''
                ];
                
                if ($userObj->updateUser($userId, $updateData)) {
                    $successMessage = 'Informațiile au fost actualizate cu succes!';
                    $userData = $userObj->getUserById($userId); // Refresh data
                } else {
                    $errorMessage = 'Eroare la actualizarea informațiilor.';
                }
                break;
                
            case 'update_contact':
                $updateData = [
                    'email' => $_POST['email'] ?? '',
                    'phone' => $_POST['phone'] ?? ''
                ];
                
                if ($userObj->updateUser($userId, $updateData)) {
                    $successMessage = 'Datele de contact au fost actualizate cu succes!';
                    $userData = $userObj->getUserById($userId);
                } else {
                    $errorMessage = 'Eroare la actualizarea datelor de contact.';
                }
                break;
                
            case 'update_company_info':
                $updateData = [
                    'company_name' => $_POST['company_name'] ?? '',
                    'cui' => $_POST['cui'] ?? '',
                    'reg_com' => $_POST['reg_com'] ?? '',
                    'bank_account' => $_POST['bank_account'] ?? '',
                    'default_order_type' => $_POST['default_order_type'] ?? 'physical'
                ];
                
                if ($userObj->updateUser($userId, $updateData)) {
                    $successMessage = 'Informațiile companiei au fost actualizate cu succes!';
                    $userData = $userObj->getUserById($userId);
                } else {
                    $errorMessage = 'Eroare la actualizarea informațiilor companiei.';
                }
                break;
                
            case 'change_password':
                $currentPassword = $_POST['current_password'] ?? '';
                $newPassword = $_POST['new_password'] ?? '';
                
                // Verify current password
                if (!password_verify($currentPassword, $userData['password'])) {
                    $errorMessage = 'Parola curentă este incorectă.';
                } elseif (strlen($newPassword) < 6) {
                    $errorMessage = 'Parola nouă trebuie să aibă cel puțin 6 caractere.';
                } else {
                    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                    if ($userObj->updateUser($userId, ['password' => $hashedPassword])) {
                        $successMessage = 'Parola a fost schimbată cu succes!';
                    } else {
                        $errorMessage = 'Eroare la schimbarea parolei.';
                    }
                }
                break;
        }
    }
}

// Get loyalty points history
require_once __DIR__ . '/includes/Loyalty.php';
$loyalty = new Loyalty();
$loyaltyHistory = $loyalty->getUserHistory($userId, 10); // Last 10 transactions
?>

    <!-- 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" href="/cont/comenzi">
                    <i class="ci-shopping-bag fs-base opacity-75 me-2"></i>
                    Comenzi
                  </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 pe-none active" 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>


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

              <!-- Page title -->
              <h1 class="h2 mb-4">Informații personale</h1>

              <?php if ($successMessage): ?>
              <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($successMessage); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
              </div>
              <?php endif; ?>

              <?php if ($errorMessage): ?>
              <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($errorMessage); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
              </div>
              <?php endif; ?>

              <!-- Basic info -->
              <div class="border-bottom py-4">
                <div class="nav flex-nowrap align-items-center justify-content-between pb-1 mb-3">
                  <div class="d-flex align-items-center gap-3 me-4">
                    <h2 class="h6 mb-0">Informații de bază</h2>
                  </div>
                  <a class="nav-link hiding-collapse-toggle text-decoration-underline p-0 collapsed" href=".basic-info" data-bs-toggle="collapse" aria-expanded="false" aria-controls="basicInfoPreview basicInfoEdit">Editează</a>
                </div>
                <div class="collapse basic-info show" id="basicInfoPreview">
                  <ul class="list-unstyled fs-sm m-0">
                    <li class="mb-1"><?php echo htmlspecialchars($userData['first_name'] . ' ' . $userData['last_name']); ?></li>
                    <?php if ($userData['phone']): ?>
                    <li><?php echo htmlspecialchars($userData['phone']); ?></li>
                    <?php endif; ?>
                    <?php if ($userData['cnp']): ?>
                    <li>CNP: <?php echo htmlspecialchars($userData['cnp']); ?></li>
                    <?php endif; ?>
                  </ul>
                </div>
                <div class="collapse basic-info" id="basicInfoEdit">
                  <form method="POST" class="row g-3 g-sm-4 needs-validation" novalidate>
                    <input type="hidden" name="action" value="update_basic_info">
                    <div class="col-sm-6">
                      <label for="first_name" class="form-label">Prenume <span class="text-danger">*</span></label>
                      <input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo htmlspecialchars($userData['first_name']); ?>" required>
                    </div>
                    <div class="col-sm-6">
                      <label for="last_name" class="form-label">Nume <span class="text-danger">*</span></label>
                      <input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo htmlspecialchars($userData['last_name']); ?>" required>
                    </div>
                    <div class="col-sm-6">
                      <label for="phone" class="form-label">Număr telefon</label>
                      <input type="text" class="form-control" id="phone" name="phone" value="<?php echo htmlspecialchars($userData['phone'] ?? ''); ?>">
                    </div>
                    <div class="col-sm-6">
                      <label for="cnp" class="form-label">CNP</label>
                      <input type="text" class="form-control" id="cnp" name="cnp" value="<?php echo htmlspecialchars($userData['cnp'] ?? ''); ?>" maxlength="13">
                    </div>
                    <div class="col-12">
                      <div class="d-flex gap-3 pt-2 pt-sm-0">
                        <button type="submit" class="btn btn-primary">Salvează modificările</button>
                        <button type="button" class="btn btn-secondary" data-bs-toggle="collapse" data-bs-target=".basic-info" aria-expanded="true" aria-controls="basicInfoPreview basicInfoEdit">Anulează</button>
                      </div>
                    </div>
                  </form>
                </div>
              </div>

              <!-- Contact -->
              <div class="border-bottom py-4">
                <div class="nav flex-nowrap align-items-center justify-content-between pb-1 mb-3">
                  <div class="d-flex align-items-center gap-3 me-4">
                    <h2 class="h6 mb-0">Contact</h2>
                  </div>
                  <a class="nav-link hiding-collapse-toggle text-decoration-underline p-0 collapsed" href=".contact-info" data-bs-toggle="collapse" aria-expanded="false" aria-controls="contactInfoPreview contactInfoEdit">Editează</a>
                </div>
                <div class="collapse contact-info show" id="contactInfoPreview">
                  <ul class="list-unstyled fs-sm m-0">
                    <li class="mb-1"><?php echo htmlspecialchars($userData['email']); ?></li>
                    <?php if ($userData['phone']): ?>
                    <li><?php echo htmlspecialchars($userData['phone']); ?> <span class="text-success ms-1">Verificat</span></li>
                    <?php endif; ?>
                  </ul>
                </div>
                <div class="collapse contact-info" id="contactInfoEdit">
                  <form method="POST" class="row g-3 g-sm-4 needs-validation" novalidate>
                    <input type="hidden" name="action" value="update_contact">
                    <div class="col-sm-6">
                      <label for="email" class="form-label">Adresă email <span class="text-danger">*</span></label>
                      <div class="position-relative">
                        <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($userData['email']); ?>" required>
                        <div class="invalid-feedback">Te rugăm să introduci o adresă de email validă!</div>
                      </div>
                    </div>
                    <div class="col-sm-6">
                      <label for="phone_contact" class="form-label">Număr telefon</label>
                      <div class="position-relative">
                        <input type="text" class="form-control" id="phone_contact" name="phone" value="<?php echo htmlspecialchars($userData['phone'] ?? ''); ?>" placeholder="+40 (___) ___ __ __">
                        <div class="invalid-feedback">Te rugăm să introduci numărul de telefon!</div>
                      </div>
                    </div>
                    <div class="col-12">
                      <div class="d-flex gap-3 pt-2 pt-sm-0">
                        <button type="submit" class="btn btn-primary">Salvează modificările</button>
                        <button type="button" class="btn btn-secondary" data-bs-toggle="collapse" data-bs-target=".contact-info" aria-expanded="true" aria-controls="contactInfoPreview contactInfoEdit">Anulează</button>
                      </div>
                    </div>
                  </form>
                </div>
              </div>

              <!-- Company info (for legal entities) -->
              <div class="border-bottom py-4">
                <div class="nav flex-nowrap align-items-center justify-content-between pb-1 mb-3">
                  <div class="d-flex align-items-center gap-3 me-4">
                    <h2 class="h6 mb-0">Informații companie</h2>
                  </div>
                  <a class="nav-link hiding-collapse-toggle text-decoration-underline p-0 collapsed" href=".company-info" data-bs-toggle="collapse" aria-expanded="false" aria-controls="companyInfoPreview companyInfoEdit">Editează</a>
                </div>
                <div class="collapse company-info show" id="companyInfoPreview">
                  <ul class="list-unstyled fs-sm m-0">
                    <?php if ($userData['company_name']): ?>
                    <li class="mb-1"><?php echo htmlspecialchars($userData['company_name']); ?></li>
                    <?php if ($userData['cui']): ?>
                    <li>CUI: <?php echo htmlspecialchars($userData['cui']); ?></li>
                    <?php endif; ?>
                    <?php if ($userData['reg_com']): ?>
                    <li>Nr. Reg. Com.: <?php echo htmlspecialchars($userData['reg_com']); ?></li>
                    <?php endif; ?>
                    <?php else: ?>
                    <li class="text-body-secondary">Nu sunt informații despre companie.</li>
                    <?php endif; ?>
                  </ul>
                </div>
                <div class="collapse company-info" id="companyInfoEdit">
                  <form method="POST" class="row g-3 g-sm-4 needs-validation" novalidate>
                    <input type="hidden" name="action" value="update_company_info">
                    <div class="col-sm-6">
                      <label for="company_name" class="form-label">Nume companie</label>
                      <input type="text" class="form-control" id="company_name" name="company_name" value="<?php echo htmlspecialchars($userData['company_name'] ?? ''); ?>">
                    </div>
                    <div class="col-sm-6">
                      <label for="cui" class="form-label">CUI</label>
                      <input type="text" class="form-control" id="cui" name="cui" value="<?php echo htmlspecialchars($userData['cui'] ?? ''); ?>">
                    </div>
                    <div class="col-sm-6">
                      <label for="reg_com" class="form-label">Nr. Reg. Com.</label>
                      <input type="text" class="form-control" id="reg_com" name="reg_com" value="<?php echo htmlspecialchars($userData['reg_com'] ?? ''); ?>">
                    </div>
                    <div class="col-sm-6">
                      <label for="bank_account" class="form-label">Cont bancar</label>
                      <input type="text" class="form-control" id="bank_account" name="bank_account" value="<?php echo htmlspecialchars($userData['bank_account'] ?? ''); ?>">
                    </div>
                    <div class="col-sm-6">
                      <label for="default_order_type" class="form-label">Tip comandă implicit</label>
                      <select class="form-select" id="default_order_type" name="default_order_type">
                        <option value="physical" <?php echo ($userData['default_order_type'] ?? 'physical') === 'physical' ? 'selected' : ''; ?>>Persoană fizică</option>
                        <option value="legal" <?php echo ($userData['default_order_type'] ?? 'physical') === 'legal' ? 'selected' : ''; ?>>Persoană juridică</option>
                      </select>
                    </div>
                    <div class="col-12">
                      <div class="d-flex gap-3 pt-2 pt-sm-0">
                        <button type="submit" class="btn btn-primary">Salvează modificările</button>
                        <button type="button" class="btn btn-secondary" data-bs-toggle="collapse" data-bs-target=".company-info" aria-expanded="true" aria-controls="companyInfoPreview companyInfoEdit">Anulează</button>
                      </div>
                    </div>
                  </form>
                </div>
              </div>

              <!-- Password -->
              <div class="border-bottom py-4">
                <div class="nav flex-nowrap align-items-center justify-content-between pb-1 mb-3">
                  <div class="d-flex align-items-center gap-3 me-4">
                    <h2 class="h6 mb-0">Parolă</h2>
                  </div>
                  <a class="nav-link hiding-collapse-toggle text-decoration-underline p-0 collapsed" href=".password-change" data-bs-toggle="collapse" aria-expanded="false" aria-controls="passChangePreview passChangeEdit">Editează</a>
                </div>
                <div class="collapse password-change show" id="passChangePreview">
                  <ul class="list-unstyled fs-sm m-0">
                    <li>**************</li>
                  </ul>
                </div>
                <div class="collapse password-change" id="passChangeEdit">
                  <form method="POST" class="row g-3 g-sm-4 needs-validation" novalidate>
                    <input type="hidden" name="action" value="change_password">
                    <div class="col-sm-6">
                      <label for="current-password" class="form-label">Parola curentă</label>
                      <div class="password-toggle">
                        <input type="password" class="form-control" id="current-password" name="current_password" placeholder="Introdu parola curentă" required>
                        <label class="password-toggle-button" aria-label="Show/hide password">
                          <input type="checkbox" class="btn-check">
                        </label>
                      </div>
                    </div>
                    <div class="col-sm-6">
                      <label for="new-password" class="form-label">Parolă nouă</label>
                      <div class="password-toggle">
                        <input type="password" class="form-control" id="new-password" name="new_password" placeholder="Creează parolă nouă" required minlength="6">
                        <label class="password-toggle-button" aria-label="Show/hide password">
                          <input type="checkbox" class="btn-check">
                        </label>
                      </div>
                    </div>
                    <div class="col-12">
                      <div class="d-flex gap-3 pt-2 pt-sm-0">
                        <button type="submit" class="btn btn-primary">Salvează modificările</button>
                        <button type="button" class="btn btn-secondary" data-bs-toggle="collapse" data-bs-target=".password-change" aria-expanded="true" aria-controls="passChangePreview passChangeEdit">Anulează</button>
                      </div>
                    </div>
                  </form>
                </div>
              </div>

              <!-- Delete account -->
              <div class="pt-3 mt-2 mt-sm-3">
                <h2 class="h6">Șterge contul</h2>
                <p class="fs-sm">Când ștergi contul, profilul tău public va fi dezactivat imediat. Dacă îți schimbi părerea înainte de 14 zile, conectează-te cu email-ul și parola, și îți vom trimite un link pentru a reactiva contul.</p>
                <a class="text-danger fs-sm fw-medium" href="#!" onclick="if(confirm('Ești sigur că vrei să ștergi contul? Această acțiune nu poate fi anulată.')) { window.location.href='/api/auth.php?action=delete_account'; }">Șterge contul</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- Bonuses info modal -->
    <div class="modal fade" id="bonusesModal" tabindex="-1" aria-labelledby="bonusesModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="bonusesModalLabel">Bonusurile mele</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="d-flex align-items-center justify-content-between mb-4">
              <div>
                <h6 class="mb-1">Total bonusuri</h6>
                <div class="h4 mb-0"><?php echo $userData['loyalty_points'] ?? 0; ?></div>
              </div>
              <div class="text-end">
                <div class="fs-sm text-body-secondary mb-1">Valoare</div>
                <div class="h5 mb-0"><?php echo number_format($userData['loyalty_points'] ?? 0, 2); ?> RON</div>
              </div>
            </div>
            <?php if (!empty($loyaltyHistory)): ?>
            <h6 class="mb-3">Istoric</h6>
            <div class="list-group list-group-flush">
              <?php foreach ($loyaltyHistory as $history): ?>
              <div class="list-group-item d-flex justify-content-between align-items-start px-0">
                <div>
                  <div class="fw-medium"><?php echo htmlspecialchars($history['description']); ?></div>
                  <small class="text-body-secondary"><?php echo date('d.m.Y H:i', strtotime($history['created_at'])); ?></small>
                </div>
                <span class="badge <?php echo $history['type'] === 'earned' ? 'bg-success' : 'bg-danger'; ?> rounded-pill">
                  <?php echo $history['type'] === 'earned' ? '+' : '-'; ?><?php echo $history['points']; ?>
                </span>
              </div>
              <?php endforeach; ?>
            </div>
            <?php else: ?>
            <p class="text-body-secondary text-center py-4">Nu ai istoric de bonusuri.</p>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>

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

