<?php
require_once '../config/config.php';
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Nõua sisselogimist ja sportlase õigusi
requireLogin();
if (!isAthlete()) {
    header('Location: ' . url());
    exit;
}

$user_id = $_SESSION['user_id'];
$error = '';
$success = '';

// Töötle hobuse lisamist/muutmist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_horse'])) {
    $horse_id = getPost('horse_id');
    $name = getPost('name');
    $age = getPost('age');
    $specialization = getPost('specialization');
    $notes = getPost('notes');
    
    if (empty($name)) {
        $error = 'Hobuse nimi on kohustuslik';
    } else {
        try {
            if ($horse_id) {
                // Uuenda olemasolevat hobust
                $stmt = $pdo->prepare("
                    UPDATE horses SET
                        name = ?, age = ?, specialization = ?, notes = ?
                    WHERE id = ? AND userId = ?
                ");
                $stmt->execute([$name, $age, $specialization, $notes, $horse_id, $user_id]);
                $success = 'Hobuse andmed edukalt uuendatud!';
            } else {
                // Lisa uus hobune
                $stmt = $pdo->prepare("
                    INSERT INTO horses (userId, name, age, specialization, notes)
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([$user_id, $name, $age, $specialization, $notes]);
                $success = 'Hobune edukalt lisatud!';
            }
            
        } catch(PDOException $e) {
            $error = 'Hobuse salvestamine ebaõnnestus: ' . $e->getMessage();
            error_log('Horse save error: ' . $e->getMessage());
        }
    }
}

// Töötle hobuse kustutamist
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_horse'])) {
    $horse_id = getPost('horse_id');
    
    try {
        $stmt = $pdo->prepare("DELETE FROM horses WHERE id = ? AND userId = ?");
        $stmt->execute([$horse_id, $user_id]);
        $success = 'Hobune edukalt kustutatud!';
        
    } catch(PDOException $e) {
        $error = 'Hobuse kustutamine ebaõnnestus: ' . $e->getMessage();
    }
}

// Lae kasutaja hobused
$horses = [];
try {
    $stmt = $pdo->prepare("
        SELECT * FROM horses 
        WHERE userId = ? 
        ORDER BY name ASC
    ");
    $stmt->execute([$user_id]);
    $horses = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch(PDOException $e) {
    $error = 'Hobuste laadimine ebaõnnestus: ' . $e->getMessage();
    error_log('Horses load error: ' . $e->getMessage());
}

$page_title = 'Minu hobused';
$page_description = 'Halda oma hobuste andmeid ja märkmeid.';

include '../includes/header.php';
?>

<main class="horses-main">
    <div class="container">
        <!-- Header -->
        <div class="page-header">
            <div class="page-header-content">
                <h1 class="page-title">Minu hobused</h1>
                <p class="page-subtitle">
                    Halda oma hobuste andmeid ja treeningu märkmeid
                </p>
            </div>
            <div class="page-actions">
                <button onclick="openModal('horseModal')" class="btn btn-primary">
                    <i class="icon-plus"></i>
                    <span>Lisa hobune</span>
                </button>
            </div>
        </div>

        <!-- Alerts -->
        <?php if ($error): ?>
            <div class="alert alert-error">
                <i class="icon-alert-circle"></i>
                <span><?php echo htmlspecialchars($error); ?></span>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success">
                <i class="icon-check-circle"></i>
                <span><?php echo htmlspecialchars($success); ?></span>
            </div>
        <?php endif; ?>

        <!-- Hobuste loend -->
        <div class="horses-container">
            <?php if (empty($horses)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="icon-star"></i>
                    </div>
                    <h3>Hobuseid pole veel lisatud</h3>
                    <p>Lisa oma esimene hobune, et alustada andmete pidamist</p>
                    <button onclick="openModal('horseModal')" class="btn btn-primary">
                        <i class="icon-plus"></i>
                        <span>Lisa hobune</span>
                    </button>
                </div>
            <?php else: ?>
                <div class="horses-grid">
                    <?php foreach ($horses as $horse): ?>
                        <div class="horse-card">
                            <div class="horse-header">
                                <div class="horse-avatar">
                                    <i class="icon-star"></i>
                                </div>
                                <div class="horse-actions">
                                    <button onclick="editHorse(<?php echo htmlspecialchars(json_encode($horse)); ?>)" 
                                            class="btn-icon btn-primary" title="Muuda">
                                        <i class="icon-edit"></i>
                                    </button>
                                    <form method="POST" style="display: inline;" 
                                          onsubmit="return confirm('Kas oled kindel, et tahad selle hobuse kustutada?')">
                                        <input type="hidden" name="horse_id" value="<?php echo $horse['id']; ?>">
                                        <button type="submit" name="delete_horse" class="btn-icon btn-danger" title="Kustuta">
                                            <i class="icon-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </div>

                            <div class="horse-content">
                                <h3 class="horse-name">
                                    <?php echo htmlspecialchars($horse['name']); ?>
                                </h3>

                                <div class="horse-details">
                                    <?php if ($horse['age']): ?>
                                        <div class="horse-detail">
                                            <div class="detail-label">Vanus:</div>
                                            <div class="detail-value"><?php echo $horse['age']; ?> aastat</div>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($horse['specialization']): ?>
                                        <div class="horse-detail">
                                            <div class="detail-label">Spetsialiseerumine:</div>
                                            <div class="detail-value"><?php echo htmlspecialchars($horse['specialization']); ?></div>
                                        </div>
                                    <?php endif; ?>

                                    <div class="horse-detail">
                                        <div class="detail-label">Lisatud:</div>
                                        <div class="detail-value"><?php echo formatDate($horse['createdAt']); ?></div>
                                    </div>
                                </div>

                                <?php if ($horse['notes']): ?>
                                    <div class="horse-notes">
                                        <div class="notes-label">Märkused:</div>
                                        <div class="notes-content">
                                            <?php echo nl2br(htmlspecialchars($horse['notes'])); ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Hobuse modal -->
    <div id="horseModal" class="modal">
        <div class="modal-overlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title" id="modalTitle">Lisa hobune</h3>
                    <button class="modal-close" onclick="closeModal('horseModal')">
                        <i class="icon-x"></i>
                    </button>
                </div>

                <form method="POST" class="modal-form" id="horseForm">
                    <input type="hidden" name="horse_id" id="horse_id">
                    
                    <div class="form-group">
                        <label for="name" class="form-label">Hobuse nimi *</label>
                        <input type="text" id="name" name="name" class="form-input" 
                               placeholder="Sisesta hobuse nimi" required>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="age" class="form-label">Vanus</label>
                            <input type="number" id="age" name="age" class="form-input" 
                                   min="1" max="50" placeholder="Aastad">
                        </div>

                        <div class="form-group">
                            <label for="specialization" class="form-label">Spetsialiseerumine</label>
                            <select id="specialization" name="specialization" class="form-select">
                                <option value="">Vali spetsialiseerumine</option>
                                <option value="Koolisõit">Koolisõit</option>
                                <option value="Takistussõit">Takistussõit</option>
                                <option value="Kestvusratsutamine">Kestvusratsutamine</option>
                                <option value="Üldine">Üldine</option>
                                <option value="Algaja">Algaja</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="notes" class="form-label">Märkused</label>
                        <textarea id="notes" name="notes" class="form-textarea" rows="4" 
                                  placeholder="Hobuse iseloom, iseärasused, treeningumärkmeid..."></textarea>
                    </div>

                    <div class="modal-actions">
                        <button type="button" onclick="closeModal('horseModal')" class="btn btn-secondary">
                            <i class="icon-x"></i>
                            <span>Tühista</span>
                        </button>
                        <button type="submit" name="save_horse" class="btn btn-primary btn-save">
                            <i class="icon-save"></i>
                            <span id="saveButtonText">Lisa hobune</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>

<style>
/* PARANDATUD Horses Page Styles */
.horses-main {
    padding: var(--spacing-6) 0;
    min-height: 100vh;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: var(--spacing-8);
    gap: var(--spacing-4);
}

.page-title {
    margin-bottom: var(--spacing-2);
}

.page-subtitle {
    color: var(--gray-600);
    font-size: var(--font-size-lg);
    margin: 0;
}

/* PARANDATUD Page actions nupu stiilid */
.page-actions .btn {
    padding: var(--spacing-3) var(--spacing-6);
    font-weight: 600;
    font-size: var(--font-size-base);
    box-shadow: var(--shadow);
    border: 2px solid var(--primary-color);
    background: var(--primary-color);
    color: white;
    transition: all var(--transition-fast);
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
}

.page-actions .btn:hover {
    background: var(--primary-dark);
    border-color: var(--primary-dark);
    transform: translateY(-1px);
    box-shadow: var(--shadow-lg);
}

.page-actions .btn:focus {
    outline: none;
    box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary-color) 30%, transparent);
}

/* Horses Container */
.horses-container {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    padding: var(--spacing-6);
}

/* PARANDATUD Empty State stiilid */
.empty-state {
    text-align: center;
    padding: var(--spacing-16) var(--spacing-8);
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow);
    margin: var(--spacing-4);
}

.empty-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto var(--spacing-6);
    background-color: var(--success-color);
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 2rem;
    box-shadow: var(--shadow-md);
}

.empty-state h3 {
    margin-bottom: var(--spacing-3);
    color: var(--gray-900);
    font-size: var(--font-size-xl);
    font-weight: 600;
}

.empty-state p {
    color: var(--gray-600);
    margin-bottom: var(--spacing-8);
    font-size: var(--font-size-lg);
}

/* PARANDATUD Empty state nupu stiilid */
.empty-state .btn {
    padding: var(--spacing-4) var(--spacing-8);
    font-size: var(--font-size-lg);
    font-weight: 600;
    box-shadow: var(--shadow-lg);
    transform: scale(1);
    transition: all var(--transition-fast);
    border: 2px solid var(--primary-color);
    background: var(--primary-color);
    color: white;
    border-radius: var(--radius);
    display: inline-flex;
    align-items: center;
    gap: var(--spacing-2);
    text-decoration: none;
}

.empty-state .btn:hover {
    transform: scale(1.05);
    box-shadow: var(--shadow-xl);
    background: var(--primary-dark);
    border-color: var(--primary-dark);
}

/* Horses Grid */
.horses-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: var(--spacing-6);
}

.horse-card {
    border: 1px solid var(--gray-200);
    border-radius: var(--radius-lg);
    overflow: hidden;
    transition: all var(--transition-fast);
}

.horse-card:hover {
    border-color: var(--success-color);
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}

.horse-header {
    padding: var(--spacing-4);
    background: linear-gradient(135deg, var(--success-color), #047857);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.horse-avatar {
    width: 48px;
    height: 48px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
}

.horse-actions {
    display: flex;
    gap: var(--spacing-2);
}

.btn-icon {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all var(--transition-fast);
}

.btn-primary {
    background: rgba(255, 255, 255, 0.2);
    color: white;
}

.btn-primary:hover {
    background: rgba(255, 255, 255, 0.3);
}

.btn-danger {
    background: var(--danger-color);
    color: white;
}

.btn-danger:hover {
    background: #dc2626;
}

.horse-content {
    padding: var(--spacing-5);
}

.horse-name {
    margin: 0 0 var(--spacing-4);
    font-size: var(--font-size-xl);
    font-weight: 600;
    color: var(--gray-900);
}

.horse-details {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-3);
    margin-bottom: var(--spacing-4);
}

.horse-detail {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-2) 0;
    border-bottom: 1px solid var(--gray-100);
}

.detail-label {
    font-weight: 500;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
}

.detail-value {
    color: var(--gray-900);
    font-size: var(--font-size-sm);
}

.horse-notes {
    border-top: 1px solid var(--gray-200);
    padding-top: var(--spacing-4);
}

.notes-label {
    font-weight: 500;
    color: var(--gray-700);
    margin-bottom: var(--spacing-2);
    font-size: var(--font-size-sm);
}

.notes-content {
    color: var(--gray-600);
    font-size: var(--font-size-sm);
    line-height: 1.5;
}

/* Modal Styles */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    display: none;
}

.modal.show {
    display: flex;
}

.modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: var(--spacing-4);
}

.modal-content {
    background: white;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-xl);
    width: 100%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-5) var(--spacing-6);
    border-bottom: 1px solid var(--gray-200);
}

.modal-title {
    margin: 0;
    font-size: var(--font-size-lg);
    font-weight: 600;
}

.modal-close {
    width: 32px;
    height: 32px;
    border: none;
    background: none;
    border-radius: var(--radius);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: var(--gray-400);
    transition: all var(--transition-fast);
}

.modal-close:hover {
    background: var(--gray-100);
    color: var(--gray-600);
}

.modal-form {
    padding: var(--spacing-6);
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: var(--spacing-4);
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-2);
    margin-bottom: var(--spacing-4);
}

.form-label {
    font-weight: 500;
    color: var(--gray-700);
    font-size: var(--font-size-sm);
}

.form-input,
.form-select,
.form-textarea {
    padding: var(--spacing-3);
    border: 1px solid var(--gray-300);
    border-radius: var(--radius);
    font-size: var(--font-size-sm);
    transition: border-color var(--transition-fast);
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
    outline: none;
    border-color: var(--success-color);
    box-shadow: 0 0 0 3px color-mix(in srgb, var(--success-color) 10%, transparent);
}

.form-textarea {
    resize: vertical;
    font-family: inherit;
}

/* PARANDATUD Modal actions - kontrastsemad nupud */
.modal-actions {
    display: flex;
    justify-content: flex-end;
    gap: var(--spacing-3);
    margin-top: var(--spacing-6);
    padding-top: var(--spacing-4);
    border-top: 1px solid var(--gray-200);
}

.modal-actions .btn {
    padding: var(--spacing-3) var(--spacing-6);
    border-radius: var(--radius);
    font-weight: 600;
    font-size: var(--font-size-base);
    border: 2px solid;
    cursor: pointer;
    transition: all var(--transition-fast);
    display: flex;
    align-items: center;
    gap: var(--spacing-2);
    text-decoration: none;
    min-width: 120px;
    justify-content: center;
}

/* PARANDATUD Tühista nupp */
.modal-actions .btn-secondary {
    background: white;
    color: var(--gray-600);
    border-color: var(--gray-300);
}

.modal-actions .btn-secondary:hover {
    background: var(--gray-50);
    color: var(--gray-700);
    border-color: var(--gray-400);
    transform: translateY(-1px);
    box-shadow: var(--shadow);
}

/* PARANDATUD Lisa/Salvesta nupp - väga kontrastne */
.modal-actions .btn-save,
.modal-actions .btn-primary {
    background: var(--primary-color) !important;
    color: white !important;
    border-color: var(--primary-color) !important;
    box-shadow: var(--shadow-lg) !important;
    font-weight: 700 !important;
}

.modal-actions .btn-save:hover,
.modal-actions .btn-primary:hover {
    background: var(--primary-dark) !important;
    border-color: var(--primary-dark) !important;
    transform: translateY(-2px) !important;
    box-shadow: var(--shadow-xl) !important;
}

.modal-actions .btn-save:focus,
.modal-actions .btn-primary:focus {
    outline: none !important;
    box-shadow: 0 0 0 4px color-mix(in srgb, var(--primary-color) 30%, transparent) !important;
}

/* Responsive */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: stretch;
        gap: var(--spacing-4);
    }
    
    .page-actions .btn {
        width: 100%;
        justify-content: center;
        font-size: var(--font-size-xl);
        padding: var(--spacing-4);
    }
    
    .horses-grid {
        grid-template-columns: 1fr;
    }
    
    .horse-detail {
        flex-direction: column;
        align-items: flex-start;
        gap: var(--spacing-1);
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .modal-actions {
        flex-direction: column;
        gap: var(--spacing-3);
    }
    
    .modal-actions .btn {
        width: 100%;
        padding: var(--spacing-4);
        font-size: var(--font-size-lg);
    }
    
    .empty-state .btn {
        width: 100%;
        justify-content: center;
        padding: var(--spacing-4);
        font-size: var(--font-size-xl);
    }
}
</style>

<script>
// Global modal functions
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('show');
        document.body.style.overflow = 'hidden';
        
        // Trigger custom event
        const event = new CustomEvent('show');
        modal.dispatchEvent(event);
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('show');
        document.body.style.overflow = '';
    }
}

function editHorse(horse) {
    // Fill form with horse data
    document.getElementById('horse_id').value = horse.id;
    document.getElementById('name').value = horse.name;
    document.getElementById('age').value = horse.age || '';
    document.getElementById('specialization').value = horse.specialization || '';
    document.getElementById('notes').value = horse.notes || '';
    
    // Update modal title and button
    document.getElementById('modalTitle').textContent = 'Muuda hobust';
    document.getElementById('saveButtonText').textContent = 'Salvesta muudatused';
    
    openModal('horseModal');
}

function resetForm() {
    document.getElementById('horseForm').reset();
    document.getElementById('horse_id').value = '';
    document.getElementById('modalTitle').textContent = 'Lisa hobune';
    document.getElementById('saveButtonText').textContent = 'Lisa hobune';
}

// Event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Reset form when opening modal for new horse
    const addButtons = document.querySelectorAll('button[onclick="openModal(\'horseModal\')"]');
    addButtons.forEach(button => {
        button.addEventListener('click', resetForm);
    });
    
    // Auto-focus name input when modal opens
    const modal = document.getElementById('horseModal');
    if (modal) {
        modal.addEventListener('show', function() {
            setTimeout(() => {
                const nameInput = document.getElementById('name');
                if (nameInput) {
                    nameInput.focus();
                }
            }, 100);
        });
    }
    
    // Close modal on escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const openModals = document.querySelectorAll('.modal.show');
            openModals.forEach(modal => {
                modal.classList.remove('show');
                document.body.style.overflow = '';
            });
        }
    });
    
    // Close modal on overlay click
    const modalOverlays = document.querySelectorAll('.modal-overlay');
    modalOverlays.forEach(overlay => {
        overlay.addEventListener('click', function(e) {
            if (e.target === this) {
                this.closest('.modal').classList.remove('show');
                document.body.style.overflow = '';
            }
        });
    });
    
    console.log('✅ Horses page initialized with enhanced button visibility!');
});
</script>

<?php include '../includes/footer.php'; ?>