# 🚀 HOSTIVA V6 - COMPLETE DEPLOYMENT GUIDE

## ✅ What You Have Now

You have **5 production-ready systems**:
1. ✅ **Authentication System** - Secure login/logout
2. ✅ **Full Booking API** - Complete CRUD operations
3. ✅ **Invoice Generation & Export** - CSV export with summaries
4. ✅ **Email Notification System** - Auto-send confirmations
5. ✅ **Payment Processing** - Stripe integration

---

## 📋 DEPLOYMENT CHECKLIST

### Phase 1: Installation (30 minutes)

- [ ] Copy API files to your server
  ```
  /api/controllers/auth.php
  /api/controllers/bookings_complete.php
  /api/controllers/invoices_complete.php
  /api/services/EmailService.php
  /api/services/PaymentService.php
  /api/index.php (router)
  ```

- [ ] Copy configuration
  ```
  /config/config.php (IMPORTANT: Update database credentials)
  /config/config.example.php (reference)
  ```

- [ ] Copy frontend API client
  ```
  /assets/api-client.js
  ```

### Phase 2: Database Setup (20 minutes)

- [ ] Import your database dump
  ```sql
  mysql -u root -p hostiva < /path/to/database.sql
  ```

- [ ] Verify tables exist
  ```sql
  SHOW TABLES;
  ```

- [ ] Check key tables
  - [ ] users
  - [ ] bookings
  - [ ] guests
  - [ ] folio_charges (invoices)
  - [ ] payments
  - [ ] activity_log

### Phase 3: Configuration (15 minutes)

Update `/config/config.php`:

```php
// Database
'database' => [
    'host' => 'localhost',
    'name' => 'hostiva',
    'user' => 'your_db_user',
    'password' => 'your_db_password',
]

// Email (choose one)
// Option A: Gmail
'email' => [
    'driver' => 'smtp',
    'host' => 'smtp.gmail.com',
    'port' => 587,
    'username' => 'your-email@gmail.com',
    'password' => 'your-app-password', // Generate in Gmail settings
    'encryption' => 'tls'
]

// Option B: Sendgrid
'email' => [
    'driver' => 'smtp',
    'host' => 'smtp.sendgrid.net',
    'port' => 587,
    'username' => 'apikey',
    'password' => 'SG.your-sendgrid-key',
    'encryption' => 'tls'
]

// Stripe (get from dashboard)
'stripe' => [
    'public_key' => 'pk_live_...',
    'secret_key' => 'sk_live_...',
    'webhook_secret' => 'whsec_...'
]
```

### Phase 4: Enable API Endpoints in Frontend (20 minutes)

Update `/pages/bookings.html` to use API instead of localStorage:

**BEFORE:**
```javascript
// Old way (localStorage)
const bookings = JSON.parse(localStorage.getItem('hostiva_bookings')) || [];
bookings.push(newBooking);
localStorage.setItem('hostiva_bookings', JSON.stringify(bookings));
```

**AFTER:**
```javascript
// New way (API)
const result = await API.createBooking({
    guest_id: data.guest_id,
    property_id: data.property_id,
    check_in: data.check_in,
    check_out: data.check_out,
    price: data.price
});

if (result.success) {
    showNotification('Booking created: ' + result.booking_reference);
    // Refresh bookings from API
    loadBookingsFromAPI();
}
```

---

## 🔧 API ENDPOINTS REFERENCE

### Authentication
```
POST /api/auth/login
  { email, password }
  → { success, token, user }

POST /api/auth/register
  { name, email, password, password_confirm }
  → { success, user_id }

POST /api/auth/logout
  → { success }

GET /api/auth/verify
  → { success, user }
```

### Bookings
```
GET /api/bookings?property_id=1&status=confirmed
  → { success, bookings[] }

POST /api/bookings
  { guest_id, property_id, check_in, check_out, price }
  → { success, booking_id, booking_reference, guest_token }

GET /api/bookings/{id}
  → { success, booking }

PUT /api/bookings/{id}
  { room_id, check_in, check_out, price, status, notes }
  → { success }

DELETE /api/bookings/{id}
  { reason }
  → { success }

GET /api/bookings/guest/{token}
  → { success, booking }

POST /api/bookings/{id}/guest-link
  → { success, token, link }
```

### Invoices
```
GET /api/invoices?property_id=1&status=pending
  → { success, invoices[] }

POST /api/invoices
  { booking_id }
  → { success, invoice_id, invoice_number, total }

GET /api/invoices/{id}
  → { success, invoice }

POST /api/invoices/{id}/payment
  { method, transaction_id }
  → { success }

POST /api/invoices/{id}/export-csv
  → CSV file download

POST /api/invoices/export-all
  → CSV file download
```

### Payments
```
GET /api/payments/stripe-key
  → { success, public_key }

POST /api/payments/create-intent
  { invoice_id }
  → { success, client_secret, intent_id }

POST /api/payments/confirm
  { intent_id, invoice_id }
  → { success, transaction_id }

GET /api/payments/history/{invoice_id}
  → { success, payments[] }

POST /api/payments/refund
  { transaction_id, reason }
  → { success, refund_id }
```

### Emails
```
POST /api/emails/booking-confirmation/{booking_id}
  → { success }

POST /api/emails/invoice/{invoice_id}
  → { success }

POST /api/emails/check-in-reminder/{booking_id}
  → { success }

POST /api/emails/payment-reminder/{invoice_id}
  → { success }
```

---

## 🎯 TESTING WORKFLOW

### 1. Test Authentication
```javascript
// In browser console
const login = await API.login('admin@hostiva.com', 'password123');
console.log(login); // Should show success: true, token, user
```

### 2. Test Booking Creation
```javascript
const booking = await API.createBooking({
    guest_id: 1,
    property_id: 1,
    check_in: '2026-06-15',
    check_out: '2026-06-20',
    price: 500
});
console.log(booking); // Should show success: true, booking_id
```

### 3. Test Invoice Generation
```javascript
const invoice = await API.generateInvoice(1); // booking_id
console.log(invoice); // Should show success: true, invoice_number
```

### 4. Test Email Sending
```javascript
const email = await API.sendBookingConfirmation(1); // booking_id
console.log(email); // Should show success: true
```

### 5. Test Payment
```javascript
const intent = await API.createPaymentIntent(1); // invoice_id
console.log(intent); // Should show client_secret for Stripe
```

---

## 🔐 SECURITY CHECKLIST

- [ ] Database credentials in config are secure
- [ ] Database password changed from default
- [ ] API keys (Stripe, emails) secured
- [ ] JWT secret changed in production
- [ ] HTTPS enabled (not HTTP)
- [ ] CORS configured properly
- [ ] Input validation on all APIs
- [ ] SQL injection prevention (using prepared statements ✅)
- [ ] Authentication checks on protected endpoints
- [ ] Rate limiting on login (add if missing)
- [ ] Password hashing (bcrypt ✅)

---

## 📧 SETTING UP EMAIL

### Option 1: Gmail (Easiest)
1. Go to myaccount.google.com/apppasswords
2. Generate app password
3. Use in config:
   ```php
   'username' => 'your-email@gmail.com',
   'password' => 'xxxx xxxx xxxx xxxx', // 16-char app password
   ```

### Option 2: SendGrid (Most Reliable)
1. Sign up at sendgrid.com
2. Create API key
3. Use in config:
   ```php
   'username' => 'apikey',
   'password' => 'SG.your-key-here',
   ```

### Option 3: PHP Mail (Simplest)
```php
'driver' => 'mail', // Uses system mail function
```

---

## 💳 SETTING UP STRIPE

1. Go to dashboard.stripe.com
2. Copy **Publishable Key** (starts with `pk_live_`)
3. Copy **Secret Key** (starts with `sk_live_`)
4. Go to Webhooks → Add Endpoint
   - URL: `https://yourdomain.com/hostiva/api/payments/webhook`
   - Events: `payment_intent.succeeded`, `payment_intent.payment_failed`
5. Copy Webhook Signing Secret
6. Update config.php

---

## 🚀 GOING LIVE CHECKLIST

- [ ] Database migrated and tested
- [ ] All APIs configured
- [ ] Email system working
- [ ] Stripe integration tested
- [ ] Frontend pages updated to use APIs
- [ ] Authentication working
- [ ] Bookings saving to database
- [ ] Invoices generating
- [ ] Guests receiving emails
- [ ] Payments processing
- [ ] Error handling working
- [ ] Logs being written
- [ ] HTTPS enabled
- [ ] Backups enabled
- [ ] Monitoring alerts set up

---

## 🆘 TROUBLESHOOTING

### "Database connection failed"
- Check database credentials in config.php
- Verify database exists: `SHOW DATABASES;`
- Verify user has permissions

### "API returns 404"
- Check route in API router matches endpoint
- Verify API files are in correct location
- Check error logs

### "Emails not sending"
- Test SMTP credentials separately
- Check spam folder
- Enable "Less secure apps" for Gmail
- Check error logs for SMTP errors

### "Payment not processing"
- Verify Stripe keys are correct (test vs live)
- Check webhook is registered
- Test with Stripe test card: `4242 4242 4242 4242`

---

## 📞 NEXT STEPS

After going live with these 5 systems:

1. **OTA Integration** (Week 2)
   - Auto-sync Airbnb bookings
   - Auto-sync Booking.com bookings
   - Calendar synchronization

2. **Advanced Housekeeping** (Week 2)
   - Task automation from bookings
   - Photo documentation
   - QA checklist system

3. **Analytics & Reporting** (Week 3)
   - Occupancy dashboards
   - Revenue reports
   - Guest analytics

4. **Guest Communication** (Week 3)
   - Message threads
   - Ticket system improvements
   - Guest request tracking

---

## 📊 PRODUCTION OPTIMIZATION

### Database Indexes
```sql
ALTER TABLE bookings ADD INDEX idx_property_status (property_id, status);
ALTER TABLE bookings ADD INDEX idx_check_in (check_in);
ALTER TABLE folio_charges ADD INDEX idx_status (status);
ALTER TABLE guests ADD INDEX idx_email (email);
```

### Enable Query Caching
```php
// In config.php
$db->setAttribute(PDO::ATTR_CACHE_QUERIES, true);
```

### Implement Rate Limiting
```php
// Limit login attempts
// Limit API calls per IP
```

---

## ✅ SUCCESS CRITERIA

When these are all working, you're ready to sell:

✅ Bookings created → Saved to database
✅ Guest portal works → Guests access bookings with token
✅ Invoices generated → Auto-export to CSV
✅ Emails sent → Guests receive confirmations
✅ Payments process → Stripe integration working
✅ All data persists → No localStorage dependency
✅ Error handling → Logs record all issues
✅ Security → Passwords hashed, tokens secure

---

**You're now production-ready! 🎉**

Need help? Check logs at `/hostiva/logs/php_errors.log`

