<?php
// pages/profile.php
require_once __DIR__ . '/../includes/header.php';

$user_id = $_SESSION['id'];
$msg = "";

// ---------------------------------------------------------
// 1. معالجة تغيير كلمة المرور
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'change_pass') {
    $current_pass = $_POST['current_password'];
    $new_pass = $_POST['new_password'];
    $confirm_pass = $_POST['confirm_password'];

    // جلب الباسورد الحالي من الداتابيز
    $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user_data = $stmt->fetch();

    if (password_verify($current_pass, $user_data['password_hash'])) {
        if ($new_pass === $confirm_pass) {
            if (strlen($new_pass) >= 6) {
                $new_hash = password_hash($new_pass, PASSWORD_DEFAULT);
                $update = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
                $update->execute([$new_hash, $user_id]);
                $msg = "<div class='alert alert-success'>تم تغيير كلمة المرور بنجاح!</div>";
            } else {
                $msg = "<div class='alert alert-warning'>كلمة المرور قصيرة جداً (يجب أن تكون 6 خانات على الأقل).</div>";
            }
        } else {
            $msg = "<div class='alert alert-danger'>كلمة المرور الجديدة غير متطابقة.</div>";
        }
    } else {
        $msg = "<div class='alert alert-danger'>كلمة المرور الحالية غير صحيحة.</div>";
    }
}

// ---------------------------------------------------------
// 2. معالجة رفع الصورة الشخصية (Avatar)
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'upload_avatar') {
    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png'];
        $ext = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed)) {
            $new_name = "avatar_" . $user_id . "_" . time() . "." . $ext;
            $upload_dir = __DIR__ . '/../assets/uploads/avatars/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            if (move_uploaded_file($_FILES['avatar']['tmp_name'], $upload_dir . $new_name)) {
                $db_path = 'assets/uploads/avatars/' . $new_name;
                $pdo->prepare("UPDATE users SET profile_pic = ? WHERE id = ?")->execute([$db_path, $user_id]);
                $msg = "<div class='alert alert-success'>تم تحديث الصورة الشخصية!</div>";
                // تحديث الجلسة للصورة الجديدة (اختياري للعرض الفوري في الهيدر)
                $_SESSION['profile_pic'] = $db_path;
            }
        } else {
            $msg = "<div class='alert alert-danger'>صيغة الملف غير مدعومة.</div>";
        }
    }
}

// ---------------------------------------------------------
// 3. معالجة التوقيع (Smart Signature Removal)
// ---------------------------------------------------------
function convertToTransparentSignature($sourcePath, $targetPath) {
    list($width, $height, $type) = getimagesize($sourcePath);
    if ($type == IMAGETYPE_JPEG) $img = imagecreatefromjpeg($sourcePath);
    elseif ($type == IMAGETYPE_PNG) $img = imagecreatefrompng($sourcePath);
    else return false;

    $newImg = imagecreatetruecolor($width, $height);
    imagealphablending($newImg, false);
    imagesavealpha($newImg, true);
    $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
    imagefill($newImg, 0, 0, $transparent);

    for ($x = 0; $x < $width; $x++) {
        for ($y = 0; $y < $height; $y++) {
            $rgb = imagecolorat($img, $x, $y);
            $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF;
            $brightness = ($r + $g + $b) / 3;
            if ($brightness > 180) imagesetpixel($newImg, $x, $y, $transparent);
            else imagesetpixel($newImg, $x, $y, imagecolorallocatealpha($newImg, $r, $g, $b, 0));
        }
    }
    imagepng($newImg, $targetPath);
    imagedestroy($img); imagedestroy($newImg);
    return true;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'upload_sig') {
    if (isset($_FILES['signature']) && $_FILES['signature']['error'] == 0) {
        $allowed = ['png', 'jpg', 'jpeg'];
        $ext = strtolower(pathinfo($_FILES['signature']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $allowed)) {
            $new_name = "sig_" . $user_id . "_" . time() . ".png";
            $upload_dir = __DIR__ . '/../assets/uploads/signatures/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            if (convertToTransparentSignature($_FILES['signature']['tmp_name'], $upload_dir . $new_name)) {
                $db_path = 'assets/uploads/signatures/' . $new_name;
                $pdo->prepare("UPDATE users SET signature_path = ? WHERE id = ?")->execute([$db_path, $user_id]);
                $msg = "<div class='alert alert-success'>تم معالجة وحفظ التوقيع بنجاح!</div>";
            }
        }
    }
}

// جلب بيانات المستخدم الحالية
$user = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$user->execute([$user_id]);
$current_user = $user->fetch();
$avatar = !empty($current_user['profile_pic']) ? "../" . $current_user['profile_pic'] : "../assets/images/default_user.png";
?>

<div class="row mb-4">
    <div class="col-12">
        <h3 class="fw-bold text-dark"><i class="bi bi-person-lines-fill"></i> الملف الشخصي والإعدادات</h3>
    </div>
</div>

<?php echo $msg; ?>

<div class="row">
    <div class="col-md-4 mb-4">
        <div class="card shadow-sm border-0 text-center p-4">
            <div class="mb-3 position-relative d-inline-block">
                <img src="<?php echo $avatar; ?>" class="rounded-circle img-thumbnail" style="width: 150px; height: 150px; object-fit: cover;">
                <button class="btn btn-sm btn-light position-absolute bottom-0 end-0 rounded-circle border" data-bs-toggle="modal" data-bs-target="#avatarModal">
                    <i class="bi bi-camera-fill"></i>
                </button>
            </div>
            <h4 class="fw-bold mb-1"><?php echo $current_user['full_name_ar']; ?></h4>
            <p class="text-muted mb-2 badge bg-light text-dark border"><?php echo ucfirst($current_user['role']); ?></p>
            <p class="text-muted small mb-0"><?php echo $current_user['email']; ?></p>
            <p class="text-muted small">تاريخ التسجيل: <?php echo date('Y-m-d', strtotime($current_user['created_at'])); ?></p>
        </div>

        <div class="card shadow-sm border-0 mt-4">
            <div class="card-header bg-white fw-bold border-bottom">التوقيع المعتمد (للطباعة)</div>
            <div class="card-body text-center">
                <div class="p-3 border bg-light rounded position-relative mb-3" style="min-height: 80px;">
                    <div style="position: absolute; inset:0; background-image: linear-gradient(45deg, #ddd 25%, transparent 25%), linear-gradient(-45deg, #ddd 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #ddd 75%), linear-gradient(-45deg, transparent 75%, #ddd 75%); background-size: 10px 10px; opacity: 0.1;"></div>
                    <?php if (!empty($current_user['signature_path'])): ?>
                        <img src="../<?php echo $current_user['signature_path']; ?>?t=<?php echo time(); ?>" class="img-fluid position-relative" style="max-height: 60px;">
                    <?php else: ?>
                        <span class="text-muted small">لا يوجد توقيع</span>
                    <?php endif; ?>
                </div>
                <button class="btn btn-outline-primary btn-sm w-100" data-bs-toggle="modal" data-bs-target="#sigModal">
                    <i class="bi bi-pen"></i> تحديث التوقيع
                </button>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold text-danger"><i class="bi bi-shield-lock"></i> تغيير كلمة المرور</h5>
            </div>
            <div class="card-body p-4">
                <form method="POST">
                    <input type="hidden" name="action" value="change_pass">
                    <div class="mb-3">
                        <label class="form-label">كلمة المرور الحالية</label>
                        <input type="password" name="current_password" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">كلمة المرور الجديدة</label>
                            <input type="password" name="new_password" class="form-control" required minlength="6">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">تأكيد كلمة المرور الجديدة</label>
                            <input type="password" name="confirm_password" class="form-control" required minlength="6">
                        </div>
                    </div>
                    <div class="text-end">
                        <button type="submit" class="btn btn-danger px-4">تحديث كلمة المرور</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="avatarModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload_avatar">
                <div class="modal-header"><h5 class="modal-title">تغيير الصورة الشخصية</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label>اختر صورة (JPG, PNG):</label>
                        <input type="file" name="avatar" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer"><button type="submit" class="btn btn-primary">حفظ الصورة</button></div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="sigModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload_sig">
                <div class="modal-header"><h5 class="modal-title">تحديث التوقيع الإلكتروني</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="alert alert-info small">صور توقيعك على ورقة بيضاء وارفعها، سيقوم النظام بإزالة الخلفية تلقائياً.</div>
                    <div class="mb-3">
                        <label>صورة التوقيع:</label>
                        <input type="file" name="signature" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer"><button type="submit" class="btn btn-success">معالجة وحفظ</button></div>
            </form>
        </div>
    </div>
</div>

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