# 🚀 Guide de Déploiement - Hippique Pro

Ce guide vous accompagne dans le déploiement de l'application Laravel Hippique Pro sur un serveur de production.

---

## 📋 Prérequis

### Serveur
- **PHP** : 8.2 ou supérieur
- **Base de données** : MySQL 8.0+ ou MariaDB 10.6+
- **Serveur web** : Nginx ou Apache
- **Redis** : recommandé pour le cache et les queues
- **Composer** : 2.x
- **Node.js** : 18.x ou supérieur (pour la compilation des assets)
- **Git**

### Extensions PHP requises
```bash
php-bcmath
php-ctype
php-curl
php-dom
php-fileinfo
php-gd
php-json
php-mbstring
php-mysql
php-openssl
php-pdo
php-tokenizer
php-xml
php-zip
```

---

## 🛠️ Installation

### 1. Cloner le projet

```bash
cd /var/www
git clone https://github.com/votre-repo/hippique-pro.git
cd hippique-pro
```

### 2. Installer les dépendances Composer

```bash
composer install --no-dev --optimize-autoloader
```

### 3. Configurer l'environnement

```bash
cp .env.example .env
php artisan key:generate
```

Éditez le fichier `.env` avec vos paramètres :

```env
APP_NAME="Hippique Pro"
APP_ENV=production
APP_URL=https://votre-domaine.com
APP_DEBUG=false

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=hippique_pro
DB_USERNAME=votre_utilisateur
DB_PASSWORD=votre_mot_de_passe

# Configuration Stripe
STRIPE_ENABLED=true
STRIPE_KEY=pk_live_votre_cle_publique
STRIPE_SECRET=sk_live_votre_cle_secrete
STRIPE_WEBHOOK_SECRET=whsec_votre_secret_webhook

# Configuration PayPal
PAYPAL_ENABLED=true
PAYPAL_MODE=live
PAYPAL_CLIENT_ID=votre_client_id
PAYPAL_CLIENT_SECRET=votre_client_secret
PAYPAL_WEBHOOK_ID=votre_webhook_id

# Configuration Email
MAIL_MAILER=smtp
MAIL_HOST=votre_serveur_smtp
MAIL_PORT=587
MAIL_USERNAME=votre_email
MAIL_PASSWORD=votre_mot_de_passe
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@votre-domaine.com
MAIL_FROM_NAME="Hippique Pro"

# Configuration Redis (recommandé)
CACHE_STORE=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
```

### 4. Créer la base de données

```bash
mysql -u root -p
CREATE DATABASE hippique_pro CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'hippique_user'@'localhost' IDENTIFIED BY 'votre_mot_de_passe_fort';
GRANT ALL PRIVILEGES ON hippique_pro.* TO 'hippique_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

### 5. Exécuter les migrations et les seeders

```bash
php artisan migrate --force
php artisan db:seed --force
```

### 6. Créer les liens symboliques

```bash
php artisan storage:link
```

### 7. Installer et compiler les assets

```bash
npm install
npm run build
```

### 8. Optimiser l'application

```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
```

---

## ⚙️ Configuration Nginx

Créez le fichier `/etc/nginx/sites-available/hippique-pro` :

```nginx
server {
    listen 80;
    listen [::]:80;
    server_name votre-domaine.com www.votre-domaine.com;
    
    # Redirection HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name votre-domaine.com www.votre-domaine.com;
    
    root /var/www/hippique-pro/public;
    index index.php index.html;
    
    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/votre-domaine.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/votre-domaine.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    
    # Logs
    access_log /var/log/nginx/hippique-pro-access.log;
    error_log /var/log/nginx/hippique-pro-error.log;
    
    # Gzip Compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
    
    # Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # Cache static files
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }
    
    # Laravel
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }
    
    # Deny access to hidden files
    location ~ /\. {
        deny all;
    }
    
    # Webhooks (pas de rate limiting)
    location ~ ^/webhooks/ {
        try_files $uri $uri/ /index.php?$query_string;
    }
}
```

Activez le site :

```bash
ln -s /etc/nginx/sites-available/hippique-pro /etc/nginx/sites-enabled/
nginx -t
systemctl reload nginx
```

---

## 🔐 Configuration SSL (Let's Encrypt)

```bash
apt-get install certbot python3-certbot-nginx
certbot --nginx -d votre-domaine.com -d www.votre-domaine.com
```

---

## ⏰ Configuration du Scheduler

Éditez la crontab :

```bash
crontab -e
```

Ajoutez :

```cron
* * * * * cd /var/www/hippique-pro && php artisan schedule:run >> /dev/null 2>&1
```

---

## 🔄 Configuration des Queues (Supervisor)

Créez le fichier `/etc/supervisor/conf.d/hippique-pro-worker.conf` :

```ini
[program:hippique-pro-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/hippique-pro/artisan queue:work --sleep=3 --tries=3 --max-time=3600
cwd=/var/www/hippique-pro
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/log/supervisor/hippique-pro-worker.log
stopwaitsecs=3600
```

Activez :

```bash
supervisorctl reread
supervisorctl update
supervisorctl start hippique-pro-worker:*
```

---

## 🔧 Configuration Stripe

### 1. Créer les produits et prix dans Stripe Dashboard

Pour chaque plan d'abonnement (Silver, Gold, Platinum) :
- Créer un produit
- Créer un prix récurrent mensuel
- Créer un prix récurrent annuel

### 2. Configurer les Webhooks

Dans Stripe Dashboard > Developers > Webhooks :
- Endpoint URL : `https://votre-domaine.com/webhooks/stripe`
- Événements à écouter :
  - `invoice.payment_succeeded`
  - `invoice.payment_failed`
  - `customer.subscription.created`
  - `customer.subscription.updated`
  - `customer.subscription.deleted`
  - `checkout.session.completed`

Copiez le secret du webhook dans `.env` :
```env
STRIPE_WEBHOOK_SECRET=whsec_...
```

---

## 🔧 Configuration PayPal

### 1. Créer les plans dans PayPal Dashboard

Pour chaque plan d'abonnement et chaque formule d'annuaire :
- Créer un produit
- Créer un plan avec facturation récurrente

### 2. Configurer les Webhooks

Dans PayPal Dashboard > Developer > My Apps & Credentials :
- Créer une app
- Configurer le webhook URL : `https://votre-domaine.com/webhooks/paypal`
- Événements à écouter :
  - `BILLING.SUBSCRIPTION.CREATED`
  - `BILLING.SUBSCRIPTION.ACTIVATED`
  - `BILLING.SUBSCRIPTION.UPDATED`
  - `BILLING.SUBSCRIPTION.EXPIRED`
  - `BILLING.SUBSCRIPTION.CANCELLED`
  - `BILLING.SUBSCRIPTION.PAYMENT.FAILED`
  - `PAYMENT.SALE.COMPLETED`

Copiez l'ID du webhook dans `.env` :
```env
PAYPAL_WEBHOOK_ID=...
```

---

## 📁 Permissions

```bash
# Propriétaire
chown -R www-data:www-data /var/www/hippique-pro

# Permissions
chmod -R 755 /var/www/hippique-pro
chmod -R 775 /var/www/hippique-pro/storage
chmod -R 775 /var/www/hippique-pro/bootstrap/cache
```

---

## 🧪 Vérification post-déploiement

### 1. Tester l'application

```bash
# Vérifier la configuration
php artisan config:show app

# Vérifier la connexion DB
php artisan db:monitor

# Vérifier les routes
php artisan route:list

# Tester les emails
php artisan tinker
Mail::raw('Test', fn($m) => $m->to('votre@email.com')->subject('Test'));
```

### 2. Tester les paiements

- Créer un compte utilisateur
- Souscrire à un plan (mode test)
- Vérifier la création de l'abonnement
- Vérifier la réception des emails

### 3. Tester l'annuaire

- Soumettre une fiche
- Effectuer un paiement
- Valider la fiche en admin
- Vérifier l'affichage public

---

## 🔄 Mises à jour

```bash
cd /var/www/hippique-pro

# Backup
php artisan backup:run

# Mise à jour du code
git pull origin main

# Mise à jour des dépendances
composer install --no-dev --optimize-autoloader
npm install && npm run build

# Migrations
php artisan migrate --force

# Cache
php artisan optimize:clear
php artisan optimize

# Redémarrer les workers
supervisorctl restart hippique-pro-worker:*
```

---

## 📊 Monitoring

### Logs importants

```bash
# Application
tail -f /var/www/hippique-pro/storage/logs/laravel.log

# Nginx
tail -f /var/log/nginx/hippique-pro-error.log

# Supervisor
tail -f /var/log/supervisor/hippique-pro-worker.log
```

### Commandes utiles

```bash
# Vérifier les workers
supervisorctl status

# Vérifier les queues
php artisan queue:monitor

# Vérifier les abonnements expirants
php artisan subscriptions:check-expiring

# Vérifier les fiches annuaire expirantes
php artisan directory:check-expiring

# Générer le sitemap
php artisan sitemap:generate
```

---

## 🆘 Dépannage

### Erreur 500

```bash
# Vérifier les logs
tail -n 50 /var/www/hippique-pro/storage/logs/laravel.log

# Vérifier les permissions
ls -la /var/www/hippique-pro/storage

# Vider le cache
php artisan optimize:clear
```

### Problèmes de paiement

```bash
# Vérifier la configuration Stripe
php artisan tinker
config('services.stripe');

# Vérifier les webhooks reçus
tail -f /var/www/hippique-pro/storage/logs/laravel.log | grep stripe
```

### Problèmes d'emails

```bash
# Tester l'envoi
php artisan tinker
Mail::raw('Test', fn($m) => $m->to('test@example.com')->subject('Test'));

# Vérifier la queue
php artisan queue:work --once
```

---

## 📞 Support

En cas de problème :
1. Consulter les logs : `storage/logs/laravel.log`
2. Vérifier la configuration : `php artisan config:show`
3. Tester les composants : `php artisan tinker`
4. Contacter le support technique
