<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/translation.php';
require_once 'includes/functions.php';

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

$db = new Database();
$conn = $db->getConnection();

// Get user data
$stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

$message = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $stmt = $conn->prepare("
            UPDATE users SET 
                full_name = :full_name,
                email = :email,
                updated_at = NOW()
            WHERE id = :id
        ");
        
        $stmt->execute([
            ':full_name' => $_POST['full_name'],
            ':email' => $_POST['email'],
            ':id' => $_SESSION['user_id']
        ]);
        
        // Update password if provided
        if (!empty($_POST['new_password'])) {
            $stmt = $conn->prepare("UPDATE users SET password = :password WHERE id = :id");
            $stmt->execute([
                ':password' => $_POST['new_password'],
                ':id' => $_SESSION['user_id']
            ]);
        }
        
        // Update session data
        $_SESSION['full_name'] = $_POST['full_name'];
        
        // Refresh user data
        $stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->bindParam(':id', $_SESSION['user_id'], PDO::PARAM_INT);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        logActivity($conn, $_SESSION['user_id'], __('update_profile_activity'), 'users', $_SESSION['user_id']);
        $message = __('profile_updated_successfully');
        
    } catch (Exception $e) {
        $error = __('error_updating_profile') . ': ' . $e->getMessage();
    }
}

// Get user statistics
$stats = [];
try {
    // Get reports count
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM antibiotic_reports WHERE reporting_pharmacist_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $stats['reports_count'] = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Get last login (if available)
    $stats['last_login'] = $user['last_login'] ?? __('not_available');
    
    // Get account creation date
    $stats['created_at'] = $user['created_at'];
    
} catch (Exception $e) {
    // Handle error silently
}

// Set page title
$page_title = __('profile_page') . ' - ' . __('system_name');

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

<!-- Main Content -->

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0"><?php echo __('profile_page'); ?></h1>
        <a href="index.php" class="btn btn-secondary">
            <i class="fas fa-arrow-right"></i> <?php echo __('back_to_home'); ?>
        </a>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="row">
        <!-- Profile Information -->
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><?php echo __('update_profile_info'); ?></h6>
                </div>
                <div class="card-body">
                    <form method="POST" class="needs-validation" novalidate>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="username" class="form-label"><?php echo __('username'); ?></label>
                                <input type="text" class="form-control" id="username" 
                                       value="<?php echo htmlspecialchars($user['username']); ?>" readonly>
                                <div class="form-text"><?php echo __('username_readonly'); ?></div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="role" class="form-label"><?php echo __('role'); ?></label>
                                <input type="text" class="form-control" id="role" 
                                       value="<?php 
                                       switch($user['role']) {
                                           case 'admin': echo __('system_admin'); break;
                                           case 'pharmacist': echo __('pharmacist'); break;
                                           case 'user': echo __('regular_user'); break;
                                           default: echo $user['role'];
                                       }
                                       ?>" readonly>
                                <div class="form-text"><?php echo __('role_set_by_admin'); ?></div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="full_name" class="form-label">الاسم الكامل *</label>
                                <input type="text" class="form-control" id="full_name" name="full_name" 
                                       value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                                <div class="invalid-feedback">
                                    يرجى إدخال الاسم الكامل
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="email" class="form-label">البريد الإلكتروني *</label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo htmlspecialchars($user['email']); ?>" required>
                                <div class="invalid-feedback">
                                    يرجى إدخال بريد إلكتروني صحيح
                                </div>
                            </div>
                        </div>

                        <hr class="my-4">

                        <h6 class="text-primary mb-3">تغيير كلمة المرور</h6>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="current_password" class="form-label">كلمة المرور الحالية</label>
                                <input type="password" class="form-control" id="current_password" name="current_password">
                                <div class="form-text">اتركه فارغاً إذا لم ترد تغيير كلمة المرور</div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label for="new_password" class="form-label">كلمة المرور الجديدة</label>
                                <input type="password" class="form-control" id="new_password" name="new_password" minlength="6">
                                <div class="form-text">6 أحرف على الأقل</div>
                            </div>
                        </div>

                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> حفظ التغييرات
                            </button>
                            <button type="reset" class="btn btn-secondary">
                                <i class="fas fa-undo"></i> إعادة تعيين
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- User Statistics -->
        <div class="col-md-4">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-info">إحصائيات المستخدم</h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="d-flex justify-content-between">
                            <span class="text-muted">عدد التقارير:</span>
                            <span class="font-weight-bold"><?php echo $stats['reports_count'] ?? 0; ?></span>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="d-flex justify-content-between">
                            <span class="text-muted">تاريخ الانضمام:</span>
                            <span class="font-weight-bold"><?php echo date('Y-m-d', strtotime($stats['created_at'])); ?></span>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="d-flex justify-content-between">
                            <span class="text-muted">آخر تسجيل دخول:</span>
                            <span class="font-weight-bold">
                                <?php 
                                if ($stats['last_login'] && $stats['last_login'] != 'غير متوفر') {
                                    echo date('Y-m-d H:i', strtotime($stats['last_login']));
                                } else {
                                    echo 'غير متوفر';
                                }
                                ?>
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card shadow mt-3">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-warning">نصائح الأمان</h6>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled mb-0">
                        <li class="mb-2">
                            <i class="fas fa-shield-alt text-success me-2"></i>
                            استخدم كلمة مرور قوية
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-lock text-warning me-2"></i>
                            لا تشارك معلومات تسجيل الدخول
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-sign-out-alt text-info me-2"></i>
                            سجل الخروج عند الانتهاء
                        </li>
                        <li>
                            <i class="fas fa-envelope text-primary me-2"></i>
                            حدث بريدك الإلكتروني بانتظام
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Form validation
(function() {
    'use strict';
    window.addEventListener('load', function() {
        var forms = document.getElementsByClassName('needs-validation');
        var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

// Password confirmation
document.getElementById('new_password').addEventListener('input', function() {
    const currentPassword = document.getElementById('current_password');
    if (this.value && !currentPassword.value) {
        currentPassword.required = true;
        currentPassword.setCustomValidity('يرجى إدخال كلمة المرور الحالية');
    } else {
        currentPassword.required = false;
        currentPassword.setCustomValidity('');
    }
});
</script>

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