<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ===== اصلاح مسیرها =====
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';

$success = '';
$error = '';

// ============================================================
// تشخیص دستگاه و دریافت UTM
// ============================================================
$device_type = detectDevice();
$utm = getUtmParams();
$ip_address = $_SERVER['REMOTE_ADDR'] ?? null;

// ============================================================
// ثبت کلیک روی لینک UTM (اگر utm_link_id وجود داشته باشد)
// ============================================================
if (!empty($utm['utm_link_id'])) {
    logUtmClick($utm['utm_link_id']);
}

// ============================================================
// دریافت لیست‌ها برای فرم
// ============================================================
$educations = $pdo->query("SELECT * FROM educations WHERE status = 'active' ORDER BY sort_order")->fetchAll();
$studyFields = $pdo->query("SELECT * FROM study_fields WHERE status = 'active' ORDER BY sort_order")->fetchAll();
$referrals = $pdo->query("SELECT * FROM referrals WHERE status = 'active' ORDER BY sort_order")->fetchAll();

// ============================================================
// پردازش فرم
// ============================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $fullname = $_POST['fullname'] ?? '';
        $phone = $_POST['phone'] ?? '';
        $emergency_phone = $_POST['emergency_phone'] ?? '';
        $national_code = $_POST['national_code'] ?? '';
        $gender = $_POST['gender'] ?? '';
        $service_status = $_POST['service_status'] ?? null;
        $education_id = $_POST['education_id'] ?? 0;
        $study_field_id = $_POST['study_field_id'] ?? 0;
        $referral_id = $_POST['referral_id'] ?? 0;
        
        // اعتبارسنجی کد ملی
        if (!preg_match('/^[0-9]{10}$/', $national_code)) {
            throw new Exception("❌ کد ملی باید دقیقاً ۱۰ رقم باشد.");
        }
        
        $checkStmt = $pdo->prepare("SELECT id FROM members WHERE national_code = ?");
        $checkStmt->execute([$national_code]);
        if ($checkStmt->fetch()) {
            throw new Exception("❌ این کد ملی قبلاً در سیستم ثبت شده است.");
        }
        
        // بررسی خدمت وظیفه برای آقایان
        if ($gender == 'مرد' && empty($service_status)) {
            throw new Exception("❌ لطفاً وضعیت خدمت وظیفه را انتخاب کنید.");
        }
        
        // ============================================================
        // ذخیره در دیتابیس
        // ============================================================
        $pdo->beginTransaction();
        
        $stmt = $pdo->prepare("INSERT INTO members (fullname, phone, emergency_phone, national_code, gender, service_status, education_id, study_field_id, payment_status, registration_status, document_status, referral_id, utm_source, utm_medium, utm_campaign, utm_link_id, device_type, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $fullname,
            $phone,
            $emergency_phone,
            $national_code,
            $gender,
            $service_status,
            $education_id,
            $study_field_id,
            'در انتظار پرداخت',
            'تماس گرفته نشده',
            'در انتظار تکمیل مدرک',
            $referral_id,
            $utm['utm_source'],
            $utm['utm_medium'],
            $utm['utm_campaign'],
            $utm['utm_link_id'],
            $device_type,
            $ip_address
        ]);
        
        $memberId = $pdo->lastInsertId();
        
        // ===== ذخیره مدارک آپلود شده =====
        $docTypes = ['profile', 'national_card', 'birth_certificate', 'last_degree', 'military_service'];
        foreach ($docTypes as $docType) {
            $hiddenName = 'doc_' . $docType;
            if (!empty($_POST[$hiddenName])) {
                $filePath = $_POST[$hiddenName];
                if (strpos($filePath, '/portal/uploads/members/') === 0) {
                    $stmt = $pdo->prepare("SELECT id FROM member_documents WHERE member_id = ? AND doc_type = ?");
                    $stmt->execute([$memberId, $docType]);
                    if (!$stmt->fetch()) {
                        $fileName = basename($filePath);
                        $stmt = $pdo->prepare("INSERT INTO member_documents (member_id, doc_type, file_name, file_path, status) VALUES (?, ?, ?, ?, 'pending')");
                        $stmt->execute([$memberId, $docType, $fileName, $filePath]);
                    }
                }
            }
        }
        
        $pdo->commit();
        
        // افزایش تعداد ثبت‌نام برای لینک UTM
        if (!empty($utm['utm_link_id'])) {
            incrementUtmRegistration($utm['utm_link_id']);
        }
        
        unset($_SESSION['temp_member_id']);
        
        $success = "✅ ثبت‌نام با موفقیت انجام شد. کارشناسان ما به زودی با شما تماس خواهند گرفت.";
        
    } catch(Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $error = $e->getMessage();
    } catch(PDOException $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $error = "❌ خطای دیتابیس: " . $e->getMessage();
    }
}

// ============================================================
// پردازش Ajax (آپلود و حذف فایل)
// ============================================================
if (isset($_POST['ajax_action'])) {
    $response = ['success' => false, 'message' => 'خطا در پردازش'];
    
    try {
        switch ($_POST['ajax_action']) {
            case 'upload_document':
                if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
                    throw new Exception('فایلی ارسال نشده است');
                }
                
                $memberId = $_SESSION['temp_member_id'] ?? 0;
                if ($memberId == 0) {
                    $stmt = $pdo->prepare("INSERT INTO members (fullname, created_at) VALUES ('موقت', NOW())");
                    $stmt->execute();
                    $memberId = $pdo->lastInsertId();
                    $_SESSION['temp_member_id'] = $memberId;
                }
                
                $result = uploadMemberDocument($_FILES['file'], $memberId, $_POST['doc_type']);
                if ($result['success']) {
                    $response = ['success' => true, 'message' => 'آپلود شد', 'file_path' => $result['file_path']];
                } else {
                    throw new Exception($result['message']);
                }
                break;
                
            case 'delete_document':
                $docType = $_POST['doc_type'];
                $memberId = $_SESSION['temp_member_id'] ?? 0;
                if ($memberId > 0) {
                    $stmt = $pdo->prepare("SELECT id, file_path FROM member_documents WHERE member_id = ? AND doc_type = ? AND status = 'pending'");
                    $stmt->execute([$memberId, $docType]);
                    $doc = $stmt->fetch();
                    if ($doc) {
                        $filePath = $_SERVER['DOCUMENT_ROOT'] . $doc['file_path'];
                        if (file_exists($filePath)) {
                            unlink($filePath);
                        }
                        $stmt = $pdo->prepare("DELETE FROM member_documents WHERE id = ?");
                        $stmt->execute([$doc['id']]);
                    }
                }
                $response = ['success' => true, 'message' => 'حذف شد'];
                break;
        }
    } catch(Exception $e) {
        $response = ['success' => false, 'message' => $e->getMessage()];
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ثبت‌نام | سامانه جامع مهدی</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/portal/assets/css/style.css">
    <style>
        body {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #6d28d9 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
            font-family: 'Vazirmatn', 'Tahoma', sans-serif;
        }
        .register-card {
            background: white;
            border-radius: 24px;
            padding: 40px;
            max-width: 750px;
            width: 100%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.15);
        }
        .register-card .header { text-align: center; margin-bottom: 25px; }
        .register-card .header .logo-icon { font-size: 3rem; color: #4f46e5; }
        .register-card .header h2 { font-weight: 700; color: #0f172a; margin: 8px 0 4px; }
        .register-card .header p { color: #94a3b8; font-size: 0.9rem; }
        .field-group { margin-bottom: 22px; }
        .field-group .group-title {
            font-size: 0.85rem;
            font-weight: 600;
            color: #0f172a;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid #e9edf2;
        }
        .field-group .group-title i { color: #4f46e5; margin-left: 8px; }
        .form-control, .form-select {
            border-radius: 10px;
            height: 44px;
            font-size: 0.9rem;
            border: 1px solid #d1d5db;
        }
        .form-control:focus, .form-select:focus {
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79,70,229,0.1);
        }
        .form-label {
            font-weight: 500;
            font-size: 0.85rem;
            color: #334155;
            margin-bottom: 4px;
        }
        .form-label .text-danger { color: #ef4444; }
        .text-muted { font-size: 0.75rem; }
        .btn-register {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            border: none;
            padding: 12px 35px;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 600;
            width: 100%;
            transition: all 0.3s ease;
        }
        .btn-register:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 30px rgba(79,70,229,0.3);
            color: white;
        }
        .btn-secondary-custom {
            padding: 12px;
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 600;
            width: 100%;
            background: #64748b;
            color: white;
            border: none;
            transition: all 0.3s ease;
            text-align: center;
            text-decoration: none;
            display: inline-block;
        }
        .btn-secondary-custom:hover {
            background: #475569;
            transform: translateY(-2px);
            color: white;
        }
        .btn-outline-secondary-custom {
            padding: 12px;
            border-radius: 12px;
            font-size: 0.9rem;
            font-weight: 500;
            width: 100%;
            text-align: center;
            text-decoration: none;
            color: #64748b;
            border: 1px solid #d1d5db;
            background: transparent;
            transition: all 0.3s ease;
            display: inline-block;
        }
        .btn-outline-secondary-custom:hover {
            background: #f1f5f9;
            border-color: #94a3b8;
            color: #475569;
        }
        .alert-custom { border-radius: 12px; padding: 12px 18px; border: none; }
        .alert-custom.alert-success { background: #dcfce7; color: #16a34a; }
        .alert-custom.alert-danger { background: #fee2e2; color: #dc2626; }
        .footer-text { text-align: center; margin-top: 20px; font-size: 0.8rem; color: #94a3b8; }

        /* ===== استایل باکس آپلود ===== */
        .upload-box {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 20px 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #fafafa;
            position: relative;
            min-height: 140px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .upload-box:hover {
            border-color: #4f46e5;
            background: #f8fafc;
        }
        .upload-box.drag-over {
            border-color: #4f46e5;
            background: #eef2ff;
        }
        .upload-box .file-input {
            display: none;
        }
        .upload-box .upload-placeholder i {
            font-size: 2.5rem;
            color: #94a3b8;
            display: block;
            margin-bottom: 6px;
        }
        .upload-box .upload-placeholder span {
            font-weight: 500;
            color: #334155;
            display: block;
        }
        .upload-box .upload-placeholder small {
            font-size: 0.7rem;
            color: #94a3b8;
        }
        .upload-box .upload-preview {
            display: none;
            width: 100%;
            position: relative;
        }
        .upload-box .upload-preview img {
            max-width: 100%;
            max-height: 150px;
            border-radius: 8px;
            object-fit: cover;
        }
        .upload-box .upload-preview .remove-file {
            position: absolute;
            top: 4px;
            left: 4px;
            width: 28px;
            height: 28px;
            padding: 0;
            border-radius: 50%;
            font-size: 0.8rem;
        }
        .upload-box .upload-status {
            margin-top: 8px;
            font-size: 0.8rem;
            padding: 4px 12px;
            border-radius: 6px;
            display: inline-block;
        }
        @media (max-width: 768px) { .register-card { padding: 24px; } .form-control, .form-select { height: 40px; } }
    </style>
</head>
<body>
    <div class="register-card">
        <div class="header">
            <div class="logo-icon"><i class="bi bi-mortarboard-fill"></i></div>
            <h2>فرم ثبت‌نام</h2>
            <p>لطفاً اطلاعات خود را به دقت وارد کنید</p>
        </div>

        <?php if(!empty($success)): ?>
            <div class="alert-custom alert-success mb-4">
                <i class="bi bi-check-circle me-1"></i> <?php echo $success; ?>
            </div>
        <?php endif; ?>
        
        <?php if(!empty($error)): ?>
            <div class="alert-custom alert-danger mb-4">
                <i class="bi bi-exclamation-circle me-1"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <?php if(empty($success)): ?>
        <form method="POST">
            <!-- ============================================================
            اطلاعات شخصی
            ============================================================ -->
            <div class="field-group">
                <div class="group-title"><i class="bi bi-person"></i> اطلاعات شخصی</div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">نام و نام خانوادگی <span class="text-danger">*</span></label>
                        <input type="text" name="fullname" class="form-control" placeholder="مثال: علی محمدی" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">شماره تماس <span class="text-danger">*</span></label>
                        <input type="text" name="phone" class="form-control" placeholder="مثال: 09123456789" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">شماره تماس ضروری</label>
                        <input type="text" name="emergency_phone" class="form-control" placeholder="مثال: 09123456789">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">کد ملی <span class="text-danger">*</span></label>
                        <input type="text" name="national_code" class="form-control" maxlength="10" pattern="[0-9]{10}" placeholder="۱۰ رقم" required>
                        <small class="text-muted">کد ملی باید دقیقاً ۱۰ رقم باشد</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">جنسیت <span class="text-danger">*</span></label>
                        <select name="gender" id="gender" class="form-select" required onchange="toggleServiceStatus()">
                            <option value="مرد">مرد</option>
                            <option value="زن">زن</option>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3" id="service_status_container" style="display: none;">
                        <label class="form-label">وضعیت خدمت وظیفه</label>
                        <select name="service_status" id="service_status" class="form-select">
                            <option value="">انتخاب کنید...</option>
                            <option value="دارای پایان خدمت">دارای پایان خدمت</option>
                            <option value="معافیت تحصیلی">معافیت تحصیلی</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- ============================================================
            اطلاعات تحصیلی
            ============================================================ -->
            <div class="field-group">
                <div class="group-title"><i class="bi bi-mortarboard"></i> اطلاعات تحصیلی</div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">مقطع تحصیلی <span class="text-danger">*</span></label>
                        <select name="education_id" class="form-select" required>
                            <?php foreach($educations as $edu): ?>
                                <option value="<?php echo $edu['id']; ?>"><?php echo htmlspecialchars($edu['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">رشته تحصیلی <span class="text-danger">*</span></label>
                        <select name="study_field_id" class="form-select" required>
                            <?php foreach($studyFields as $field): ?>
                                <option value="<?php echo $field['id']; ?>"><?php echo htmlspecialchars($field['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <!-- ============================================================
            معرف
            ============================================================ -->
            <div class="field-group">
                <div class="group-title"><i class="bi bi-share"></i> معرف</div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">معرف <span class="text-danger">*</span></label>
                        <select name="referral_id" class="form-select" required>
                            <?php foreach($referrals as $ref): ?>
                                <option value="<?php echo $ref['id']; ?>"><?php echo htmlspecialchars($ref['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>

            <!-- ============================================================
            گروه ۵: آپلود مدارک
            ============================================================ -->
            <div class="field-group">
                <div class="group-title"><i class="bi bi-upload"></i> آپلود مدارک</div>
                <p class="text-muted" style="font-size:0.85rem; margin-bottom:12px;">
                    لطفاً مدارک زیر را آپلود کنید (اختیاری - اما برای تکمیل پرونده توصیه می‌شود)
                </p>
                
                <div class="row" id="uploadContainer">
                    <!-- ۱. عکس شخصی -->
                    <div class="col-md-6 mb-3">
                        <label class="form-label">عکس شخصی</label>
                        <div class="upload-box" data-type="profile">
                            <input type="file" class="file-input" accept="image/jpeg,image/png" data-type="profile">
                            <div class="upload-preview"></div>
                            <div class="upload-placeholder">
                                <i class="bi bi-image"></i>
                                <span>انتخاب فایل</span>
                                <small>JPG, PNG (حداکثر ۵ مگابایت)</small>
                            </div>
                        </div>
                        <input type="hidden" name="doc_profile" value="">
                    </div>
                    
                    <!-- ۲. کارت ملی -->
                    <div class="col-md-6 mb-3">
                        <label class="form-label">کارت ملی</label>
                        <div class="upload-box" data-type="national_card">
                            <input type="file" class="file-input" accept="image/jpeg,image/png,application/pdf" data-type="national_card">
                            <div class="upload-preview"></div>
                            <div class="upload-placeholder">
                                <i class="bi bi-card-image"></i>
                                <span>انتخاب فایل</span>
                                <small>JPG, PNG, PDF (حداکثر ۵ مگابایت)</small>
                            </div>
                        </div>
                        <input type="hidden" name="doc_national_card" value="">
                    </div>
                    
                    <!-- ۳. شناسنامه -->
                    <div class="col-md-6 mb-3">
                        <label class="form-label">شناسنامه</label>
                        <div class="upload-box" data-type="birth_certificate">
                            <input type="file" class="file-input" accept="image/jpeg,image/png,application/pdf" data-type="birth_certificate">
                            <div class="upload-preview"></div>
                            <div class="upload-placeholder">
                                <i class="bi bi-file-text"></i>
                                <span>انتخاب فایل</span>
                                <small>JPG, PNG, PDF (حداکثر ۵ مگابایت)</small>
                            </div>
                        </div>
                        <input type="hidden" name="doc_birth_certificate" value="">
                    </div>
                    
                    <!-- ۴. آخرین مدرک تحصیلی -->
                    <div class="col-md-6 mb-3">
                        <label class="form-label">آخرین مدرک تحصیلی</label>
                        <div class="upload-box" data-type="last_degree">
                            <input type="file" class="file-input" accept="image/jpeg,image/png,application/pdf" data-type="last_degree">
                            <div class="upload-preview"></div>
                            <div class="upload-placeholder">
                                <i class="bi bi-award"></i>
                                <span>انتخاب فایل</span>
                                <small>JPG, PNG, PDF (حداکثر ۵ مگابایت)</small>
                            </div>
                        </div>
                        <input type="hidden" name="doc_last_degree" value="">
                    </div>
                    
                    <!-- ۵. کارت پایان خدمت (فقط برای آقایان) -->
                    <div class="col-md-6 mb-3" id="military_doc_container" style="display: none;">
                        <label class="form-label">کارت پایان خدمت</label>
                        <div class="upload-box" data-type="military_service">
                            <input type="file" class="file-input" accept="image/jpeg,image/png,application/pdf" data-type="military_service">
                            <div class="upload-preview"></div>
                            <div class="upload-placeholder">
                                <i class="bi bi-shield-check"></i>
                                <span>انتخاب فایل</span>
                                <small>JPG, PNG, PDF (حداکثر ۵ مگابایت)</small>
                            </div>
                        </div>
                        <input type="hidden" name="doc_military_service" value="">
                    </div>
                </div>
            </div>

            <!-- ============================================================
            دکمه‌ها
            ============================================================ -->
            <div class="d-flex flex-column gap-3 mt-4">
                <button type="submit" class="btn-register">
                    <i class="bi bi-check-circle"></i> ثبت‌نام
                </button>
                <button onclick="history.back()" class="btn-secondary-custom">
                    <i class="bi bi-arrow-right"></i> بازگشت به مرحله قبل
                </button>
                <a href="/portal/index.php" class="btn-outline-secondary-custom">
                    <i class="bi bi-house"></i> صفحه اصلی
                </a>
            </div>
        </form>
        <?php endif; ?>
        
        <div class="footer-text">
            © <?php echo date('Y') - 621; ?> - سامانه جامع مهدی | تمامی حقوق محفوظ است
        </div>
    </div>

    <script src="/portal/assets/js/upload.js"></script>
    <script>
    function toggleServiceStatus() {
        var gender = document.getElementById('gender').value;
        var container = document.getElementById('service_status_container');
        var serviceSelect = document.getElementById('service_status');
        if (gender === 'مرد') {
            container.style.display = 'block';
            serviceSelect.setAttribute('required', 'required');
        } else {
            container.style.display = 'none';
            serviceSelect.removeAttribute('required');
            serviceSelect.value = '';
        }
    }
    document.addEventListener('DOMContentLoaded', function() {
        toggleServiceStatus();
        
        // نمایش/مخفی‌سازی کارت پایان خدمت
        const genderSelect = document.getElementById('gender');
        const militaryContainer = document.getElementById('military_doc_container');
        if (genderSelect && militaryContainer) {
            function toggleMilitaryDoc() {
                militaryContainer.style.display = genderSelect.value === 'مرد' ? 'block' : 'none';
            }
            genderSelect.addEventListener('change', toggleMilitaryDoc);
            toggleMilitaryDoc();
        }
    });
    </script>
</body>
</html>