# Organization Management & Sponsor Logos Plan

## Overview
Plan to add organization management, sponsor logos on landing page, and statistics display.

---

## 1. Organization Management System

### 1.1 Database Schema Changes

#### New Model: `Organization` (`app/models/organization.py`)

```python
class Organization(db.Model):
    __tablename__ = "organizations"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False, index=True)
    name_ar = db.Column(db.String(255))
    slug = db.Column(db.String(255), unique=True, nullable=False, index=True)
    description = db.Column(db.Text)
    description_ar = db.Column(db.Text)

    # Logo
    logo_url = db.Column(db.String(500))

    # Organization Type
    org_type = db.Column(db.String(50), default="company")  # company, incubator, factory, government, other

    # Contact
    website_url = db.Column(db.String(500))
    email = db.Column(db.String(255))
    phone = db.Column(db.String(50))

    # Address
    address = db.Column(db.String(500))
    city = db.Column(db.String(100))
    country = db.Column(db.String(100))

    # Sponsorship Tier (for landing page display)
    sponsor_tier = db.Column(db.String(20))  # platinum, gold, silver, bronze, none

    # Status
    is_active = db.Column(db.Boolean, default=True)
    is_verified = db.Column(db.Boolean, default=False)

    # Timestamps
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # Relationships
    users = db.relationship("User", backref="organization")
    sponsor_profile = db.relationship("SponsorProfile", backref="organization", uselist=False)

    def __repr__(self):
        return f"<Organization {self.id}: {self.name}>"
```

#### New Model: `SponsorProfile` (`app/models/sponsor.py`)

```python
class SponsorProfile(db.Model):
    __tablename__ = "sponsor_profiles"

    id = db.Column(db.Integer, primary_key=True)
    organization_id = db.Column(db.Integer, db.ForeignKey("organizations.id"), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)  # Admin contact

    # Display Settings
    logo_url = db.Column(db.String(500))  # Can override org logo
    website_url = db.Column(db.String(500))
    tagline = db.Column(db.String(255))
    tagline_ar = db.Column(db.String(255))

    # Sponsorship Info
    tier = db.Column(db.String(20), default="bronze")  # platinum, gold, silver, bronze
    monthly_contribution = db.Column(db.Numeric(10, 2))

    # Status
    status = db.Column(db.String(20), default="pending")  # pending, approved, rejected, inactive
    display_on_landing = db.Column(db.Boolean, default=False)
    display_order = db.Column(db.Integer, default=0)

    # Timestamps
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    approved_at = db.Column(db.DateTime)

    def __repr__(self):
        return f"<SponsorProfile {self.id}: {self.organization_id}>"
```

#### Update: `User` Model

```python
# Add to app/models/user.py
organization_id = db.Column(db.Integer, db.ForeignKey("organizations.id"), nullable=True)
```

### 1.2 Admin Routes

#### Organization Management Routes (`app/routes/admin.py`)

```python
# List all organizations
@admin_bp.route("/organizations")
@admin_required
def organizations():
    page = request.args.get("page", 1, type=int)
    q = request.args.get("q", "").strip()
    query = Organization.query
    if q:
        query = query.filter(Organization.name.ilike(f"%{q}%") | Organization.name_ar.ilike(f"%{q}%"))
    pagination = query.order_by(Organization.created_at.desc()).paginate(page=page, per_page=20, error_out=False)
    return render_template("admin/organizations.html", pagination=pagination, q=q)

# Create organization
@admin_bp.route("/organizations/create", methods=["GET", "POST"])
@admin_required
def create_organization():
    if request.method == "POST":
        # Handle form submission
        pass
    return render_template("admin/organization_form.html")

# Edit organization
@admin_bp.route("/organizations/<int:org_id>/edit", methods=["GET", "POST"])
@admin_required
def edit_organization(org_id):
    # Handle edit
    pass

# Delete organization
@admin_bp.route("/organizations/<int:org_id>/delete", methods=["POST"])
@admin_required
def delete_organization(org_id):
    # Handle delete (soft delete recommended)
    pass
```

#### Sponsor Management Routes

```python
# Sponsor profiles
@admin_bp.route("/sponsors")
@admin_required
def sponsors():
    # List all sponsor profiles
    pass

@admin_bp.route("/sponsors/<int:sponsor_id>/approve", methods=["POST"])
@admin_required
def approve_sponsor(sponsor_id):
    # Approve sponsor
    pass

@admin_bp.route("/sponsors/<int:sponsor_id>/reject", methods=["POST"])
@admin_required
def reject_sponsor(sponsor_id):
    # Reject sponsor
    pass
```

### 1.3 Registration Form Update

Update `app/templates/auth/register.html` to include organization selection:

```html
<!-- Organization Selection -->
<div id="organizationField" class="hidden">
    <label class="block text-sm font-medium text-slate-300 mb-2">المنظمة / الشركة</label>
    <select name="organization_id" id="organizationSelect"
            class="appearance-none relative block w-full px-4 py-4 rounded-xl bg-black/50 border border-white/10 text-white focus:outline-none focus:ring-2 focus:ring-gold-500/50 transition">
        <option value="">اختر منظمة...</option>
        <!-- Organizations loaded via AJAX -->
    </select>
    <p class="text-xs text-slate-500 mt-1">إذا كانت منظمتك غير موجودة، اختر "أخرى"</p>
</div>
```

Update `app/routes/auth.py`:

```python
# In register() function, add:
organization_id = request.form.get("organization_id")
if organization_id:
    try:
        user.organization_id = int(organization_id)
    except ValueError:
        pass
```

---

## 2. Sponsor Logos on Landing Page

### 2.1 Infinite Horizontal Scroll Section

Add to `app/templates/landing.html` after the MBS quote section (around line 45):

```html
<!-- Sponsor Logos Section -->
<div class="relative py-12 overflow-hidden bg-gradient-to-b from-slate-900/50 to-transparent">
    <div class="text-center mb-8">
        <h3 class="text-lg font-serif font-bold text-gold-400">{{ _('landing.sponsors_title') }}</h3>
    </div>

    <!-- Infinite Scroll Container -->
    <div class="relative w-full overflow-hidden">
        <div class="flex animate-scroll-left hover:pause-scroll" id="sponsorLogos">
            <!-- Logos will be loaded dynamically -->
            {% for sponsor in sponsors %}
            <a href="{{ sponsor.website_url or '#' }}" target="_blank" rel="noopener noreferrer"
               class="flex-shrink-0 px-8 py-4 glass rounded-2xl mx-3 hover:bg-white/10 transition group">
                {% if sponsor.logo_url %}
                <img src="{{ sponsor.logo_url }}" alt="{{ sponsor.organization.name }}"
                     class="h-12 w-auto object-contain opacity-70 group-hover:opacity-100 transition">
                {% else %}
                <span class="text-xl text-slate-400">{{ sponsor.organization.name }}</span>
                {% endif %}
            </a>
            {% endfor %}
            <!-- Duplicate for seamless loop -->
            {% for sponsor in sponsors %}
            <a href="{{ sponsor.website_url or '#' }}" target="_blank" rel="noopener noreferrer"
               class="flex-shrink-0 px-8 py-4 glass rounded-2xl mx-3 hover:bg-white/10 transition group">
                {% if sponsor.logo_url %}
                <img src="{{ sponsor.logo_url }}" alt="{{ sponsor.organization.name }}"
                     class="h-12 w-auto object-contain opacity-70 group-hover:opacity-100 transition">
                {% else %}
                <span class="text-xl text-slate-400">{{ sponsor.organization.name }}</span>
                {% endif %}
            </a>
            {% endfor %}
        </div>
    </div>
</div>
```

### 2.2 CSS Animation

Add to base CSS:

```css
@keyframes scrollLeft {
    0% { transform: translateX(0); }
    100% { transform: translateX(-50%); }
}

.animate-scroll-left {
    animation: scrollLeft 40s linear infinite;
}

.hover\:pause-scroll:hover {
    animation-play-state: paused;
}
```

### 2.3 Landing Page Route Update

Update `app/routes/landing.py` (or main route):

```python
@main_bp.route("/")
def landing():
    from app.models.organization import SponsorProfile, Organization

    # Get approved sponsors ordered by display order
    sponsors = db.session.query(SponsorProfile, Organization).join(
        Organization, SponsorProfile.organization_id == Organization.id
    ).filter(
        SponsorProfile.status == "approved",
        SponsorProfile.display_on_landing == True,
        Organization.is_active == True
    ).order_by(SponsorProfile.display_order.asc(), SponsorProfile.id.asc()).all()

    sponsors_with_org = [{"sponsor": s, "organization": o} for s, o in sponsors]

    return render_template("landing.html", sponsors=sponsors_with_org)
```

---

## 3. Landing Page Statistics

### 3.1 Stats Section

Replace existing stats section in `app/templates/landing.html` (around line 781):

```html
<!-- Stats Section with Real Counts -->
<div class="relative py-20 bg-gradient-to-b from-blue-950/20 to-transparent">
    <div class="max-w-7xl mx-auto px-4">
        <div class="text-center mb-12">
            <h2 class="text-3xl md:text-4xl font-serif font-bold text-white mb-4">{{ _('landing.stats_title') }}</h2>
            <p class="text-slate-400 max-w-2xl mx-auto">{{ _('landing.stats_subtitle') }}</p>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 gap-6 max-w-5xl mx-auto mb-12">
            <!-- Users Count -->
            <div class="glass p-6 rounded-xl text-center">
                <div class="text-3xl md:text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-purple-500">
                    {{ stats.users_count }}
                </div>
                <div class="text-xs text-slate-400 mt-2">{{ _('landing.stats_users_label') }}</div>
            </div>

            <!-- Studies/Reports Count -->
            <div class="glass p-6 rounded-xl text-center">
                <div class="text-3xl md:text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 to-cyan-500">
                    {{ stats.reports_count }}
                </div>
                <div class="text-xs text-slate-400 mt-2">{{ _('landing.stats_studies_label') }}</div>
            </div>

            <!-- Sponsors Count -->
            <div class="glass p-6 rounded-xl text-center">
                <div class="text-3xl md:text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-gold-400 to-orange-500">
                    {{ stats.sponsors_count }}
                </div>
                <div class="text-xs text-slate-400 mt-2">{{ _('landing.stats_sponsors_label') }}</div>
            </div>

            <!-- Organizations Count -->
            <div class="glass p-6 rounded-xl text-center">
                <div class="text-3xl md:text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-pink-400 to-red-500">
                    {{ stats.organizations_count }}
                </div>
                <div class="text-xs text-slate-400 mt-2">{{ _('landing.stats_organizations_label') }}</div>
            </div>
        </div>
    </div>
</div>
```

### 3.2 Route Update

Update landing route to include stats:

```python
@main_bp.route("/")
def landing():
    from app.models.user import User
    from app.models.report import Report
    from app.models.organization import Organization, SponsorProfile

    # Stats
    stats = {
        "users_count": User.query.count(),
        "reports_count": Report.query.count(),
        "sponsors_count": SponsorProfile.query.filter_by(status="approved").count(),
        "organizations_count": Organization.query.filter_by(is_active=True).count()
    }

    # Sponsors for logo carousel
    sponsors = db.session.query(SponsorProfile, Organization).join(
        Organization, SponsorProfile.organization_id == Organization.id
    ).filter(
        SponsorProfile.status == "approved",
        SponsorProfile.display_on_landing == True,
        Organization.is_active == True
    ).order_by(SponsorProfile.display_order.asc()).all()

    return render_template("landing.html", stats=stats, sponsors=sponsors)
```

---

## 4. Sponsor Profile Management

### 4.1 User Profile - Sponsor Request

Add sponsor request section to `app/templates/auth/profile.html`:

```html
<!-- Sponsor Request Section -->
<div class="glass p-8 rounded-2xl mt-6" id="sponsorSection">
    <h2 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
        <span class="text-gold-400">&#127970;</span> طلب الرعاية
    </h2>
    <p class="text-slate-400 text-sm mb-4">
        إذا كنت ترغب في عرض شعار شركتك على الصفحة الرئيسية كراعي، يمكنك تقديم طلب هنا.
    </p>

    {% if current_user.sponsor_request %}
    <div class="p-4 bg-{% if current_user.sponsor_request.status == 'approved' %}emerald{% elif current_user.sponsor_request.status == 'rejected' %}red{% else %}yellow{% endif %}-500/20 rounded-xl border border-{% if current_user.sponsor_request.status == 'approved' %}emerald{% elif current_user.sponsor_request.status == 'rejected' %}red{% else %}yellow{% endif %}-500/30 mb-4">
        <div class="flex items-center gap-2">
            <span class="text-{% if current_user.sponsor_request.status == 'approved' %}emerald{% elif current_user.sponsor_request.status == 'rejected' %}red{% else %}yellow{% endif %}-400">
                {% if current_user.sponsor_request.status == 'approved' %}&#10003;
                {% elif current_user.sponsor_request.status == 'rejected' %}&#10005;
                {% else %}&#9888;{% endif %}
            </span>
            <span class="text-sm text-slate-300">
                حالة طلبك: <strong class="text-white">{{ current_user.sponsor_request.status|capitalize }}</strong>
            </span>
        </div>
    </div>
    {% else %}
    <form method="POST" action="{{ url_for('auth.submit_sponsor_request') }}" class="space-y-4">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <div>
            <label class="block text-xs text-slate-400 mb-1">رابط الشعار (URL)</label>
            <input type="url" name="logo_url" placeholder="https://..." class="w-full bg-black/20 border border-white/10 rounded-lg px-3 py-2 text-white text-sm">
        </div>
        <div>
            <label class="block text-xs text-slate-400 mb-1">مستوى الرعاية</label>
            <select name="tier" class="w-full bg-black/20 border border-white/10 rounded-lg px-3 py-2 text-white text-sm">
                <option value="bronze">برونزي</option>
                <option value="silver">فضي</option>
                <option value="gold">ذهبي</option>
                <option value="platinum">بلاتيني</option>
            </select>
        </div>
        <div>
            <label class="block text-xs text-slate-400 mb-1">ملاحظات</label>
            <textarea name="notes" rows="2" class="w-full bg-black/20 border border-white/10 rounded-lg px-3 py-2 text-white text-sm"></textarea>
        </div>
        <button type="submit" class="bg-gold-500 text-black px-6 py-2 rounded-lg font-bold hover:bg-gold-400 transition">إرسال الطلب</button>
    </form>
    {% endif %}
</div>
```

---

## 5. File Upload Handler

### 5.1 Upload Helper

Add `app/utils/uploads.py`:

```python
import os
import uuid
from werkzeug.utils import secure_filename
from flask import current_app

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'}
MAX_FILE_SIZE = 2 * 1024 * 1024  # 2MB

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def upload_logo(file):
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        unique_name = f"{uuid.uuid4().hex}_{filename}"
        upload_path = os.path.join(current_app.config['UPLOAD_FOLDER'], 'logos', unique_name)

        # Create directory if doesn't exist
        os.makedirs(os.path.dirname(upload_path), exist_ok=True)

        file.save(upload_path)
        return f"/static/uploads/logos/{unique_name}"
    return None
```

### 5.2 Route for Logo Upload

```python
@auth_bp.route("/profile/upload-logo", methods=["POST"])
@login_required
def upload_sponsor_logo():
    from werkzeug.utils import secure_filename

    if 'logo' not in request.files:
        return jsonify({"error": "No file uploaded"}), 400

    file = request.files['logo']
    if file.filename == '':
        return jsonify({"error": "No file selected"}), 400

    logo_url = upload_logo(file)
    if logo_url:
        return jsonify({"logo_url": logo_url})
    return jsonify({"error": "Invalid file type"}), 400
```

---

## 6. Migration Script

Create `migrations/add_organization_system.py`:

```python
from app.extensions import db
from app.models.organization import Organization
from app.models.sponsor import SponsorProfile
from app.models.user import User

def migrate():
    """Migration script to add organization system."""
    # Create organizations table
    db.create_all()

    print("Organization system migration completed!")

if __name__ == "__main__":
    from app import create_app
    app = create_app()
    with app.app_context():
        migrate()
```

---

## 7. Internationalization

Add translation keys to `app/translations/ar/LC_MESSAGES/messages.po` and English:

```po
msgid "landing.sponsors_title"
msgstr "شركاء النجاح والرعاة"

msgid "landing.stats_users_label"
msgstr "مستخدم نشط"

msgid "landing.stats_studies_label"
msgstr "دراسة منشورة"

msgid "landing.stats_sponsors_label"
msgstr "راعي"

msgid "landing.stats_organizations_label"
msgstr "منظمة"
```

---

## 8. Recommendations & Improvements

### 8.1 Additional Features

1. **Organization Hierarchy**
   - Parent organization support for franchises/branches
   - Department/team structure within organizations

2. **Organization Billing**
   - Organization-level subscription management
   - Seat-based pricing for teams

3. **Sponsorship Analytics**
   - Click tracking for sponsor logos
   - Impressions calculation
   - ROI reports for sponsors

4. **Admin Approval Workflow**
   - Email notifications for new sponsor requests
   - Bulk approve/reject actions
   - Sponsor tier upgrade/downgrade

5. **Logo Optimization**
   - Automatic image optimization on upload
   - Generate multiple sizes (light/dark mode)
   - SVG support for vector logos

6. **Advanced Sponsor Features**
   - Sponsor spotlight rotation (randomize order)
   - Featured sponsors with larger display
   - Sponsor profiles detail pages

7. **User Experience**
   - Organization search in registration (AJAX autocomplete)
   - "Request to add organization" form
   - Organization invitation system

### 8.2 Security Considerations

1. **File Upload Security**
   - Validate file content (not just extension)
   - Sanitize SVG files (remove scripts)
   - Rate limit logo uploads

2. **Admin Actions Logging**
   - Log all organization CRUD operations
   - Track sponsor approval actions
   - Audit trail for statistics changes

3. **Access Control**
   - Organization admin roles within org
   - Limited access to organization data
   - Sensitive info protection

### 8.3 Performance Optimizations

1. **Caching**
   - Cache sponsor logos list
   - Cache statistics counts
   - CDN for logo images

2. **Database Indexes**
   - Index organization.name, name_ar
   - Index sponsor_profile.status, display_order
   - Index user.organization_id

3. **Lazy Loading**
   - Infinite scroll for sponsor logos
   - Lazy load logos below fold
   - Intersection Observer for animation

### 8.4 UI/UX Improvements

1. **Landing Page**
   - Animated counter for statistics
   - Hover effects on sponsor logos
   - Mobile-responsive logo carousel

2. **Registration Flow**
   - Multi-step registration wizard
   - Organization type affects form fields
   - Visual feedback for organization selection

3. **Admin Dashboard**
   - Organization management with map view
   - Bulk actions for sponsors
   - Organization statistics cards

---

## 9. Implementation Priority

### Phase 1: Core Organization System
- [ ] Create Organization and SponsorProfile models
- [ ] Create admin CRUD for organizations
- [ ] Update User model with organization_id
- [ ] Run migration

### Phase 2: Registration Integration
- [ ] Update registration form with org selection
- [ ] Add AJAX search for organizations
- [ ] Update auth route to handle org_id

### Phase 3: Sponsor Management
- [ ] Create SponsorProfile admin routes
- [ ] Add sponsor approval workflow
- [ ] Add user sponsor request form

### Phase 4: Landing Page
- [ ] Add infinite scroll sponsor logos
- [ ] Update statistics with real counts
- [ ] Add CSS animations

### Phase 5: File Upload
- [ ] Create upload utility
- [ ] Add logo upload route
- [ ] Integrate with forms

### Phase 6: Polish & Improvements
- [ ] Add analytics tracking
- [ ] Optimize caching
- [ ] Add notification system

---

## 10. Files to Create/Modify

### New Files
- `app/models/organization.py` - Organization and SponsorProfile models
- `app/utils/uploads.py` - File upload utilities
- `app/templates/admin/organizations.html` - Org list
- `app/templates/admin/organization_form.html` - Org create/edit
- `app/templates/admin/sponsors.html` - Sponsor list
- `migrations/add_organization_system.py` - Migration script

### Modified Files
- `app/models/user.py` - Add organization_id
- `app/routes/admin.py` - Add org/sponsor routes
- `app/routes/auth.py` - Update register, add upload
- `app/templates/auth/register.html` - Add org selection
- `app/templates/auth/profile.html` - Add sponsor request
- `app/templates/landing.html` - Add logos & stats
- `app/templates/base.html` - Add CSS for scroll
- `app/translations/*.po` - Add translations
- `app/routes/__init__.py` - Register routes

### Static Files
- `app/static/uploads/logos/` - Sponsor logo uploads (create directory)
