<?php
require_once 'config.php';
require_once 'functions.php';

// Get database connection
$pdo = getDBConnection();

// Get client ID from URL
$client_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$client_id) {
    header('Location: clients.php');
    exit;
}

// Get client information
$client = getClientById($client_id);
if (!$client) {
    header('Location: clients.php');
    exit;
}

$message = '';
$error = '';

// Handle file upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document'])) {
    $document_name = sanitizeInput($_POST['document_name']);
    $document_type = sanitizeInput($_POST['document_type']);
    
    if (empty($document_name)) {
        $error = "Моля, въведете име на документа.";
    } else {
        $upload_dir = 'uploads/';
        $file = $_FILES['document'];
        
        if ($file['error'] === UPLOAD_ERR_OK) {
            $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $safe_filename = preg_replace('/[^a-zA-Z0-9_-]/', '_', $document_name) . '_' . time() . '.' . $file_extension;
            $file_path = $upload_dir . $safe_filename;
            
            if (move_uploaded_file($file['tmp_name'], $file_path)) {
                if (addClientDocument($client_id, $document_name, $file_path, $document_type)) {
                    $message = "Документът беше качен успешно.";
                } else {
                    $error = "Грешка при запазване на документа в базата данни.";
                    unlink($file_path); // Delete uploaded file if database insert failed
                }
            } else {
                $error = "Грешка при качване на файла.";
            }
        } else {
            $error = "Грешка при качване на файла: " . $file['error'];
        }
    }
}

// Handle document deletion
if (isset($_GET['delete_doc'])) {
    $doc_id = (int)$_GET['delete_doc'];
    
    // Get document info to delete file
    $stmt = $pdo->prepare("SELECT file_path FROM client_documents WHERE id = ? AND client_id = ?");
    $stmt->execute([$doc_id, $client_id]);
    $doc = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($doc && deleteClientDocument($doc_id)) {
        if (file_exists($doc['file_path'])) {
            unlink($doc['file_path']);
        }
        $message = "Документът беше изтрит успешно.";
    } else {
        $error = "Грешка при изтриване на документа.";
    }
}

// Get client documents
$documents = getClientDocuments($client_id);

// Get client offers and protocols
$offers = [];
$protocols = [];

// Get offers where this client is recipient
$stmt = $pdo->prepare("SELECT * FROM offers WHERE recipient LIKE ? ORDER BY offer_date DESC");
$stmt->execute(['%' . $client['name'] . '%']);
$offers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get protocols where this client is issuer
$stmt = $pdo->prepare("SELECT * FROM protocols WHERE issuer LIKE ? ORDER BY protocol_date DESC");
$stmt->execute(['%' . $client['name'] . '%']);
$protocols = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="bg">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Клиентско досие - <?php echo htmlspecialchars($client['name']); ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 80%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
            border-radius: 10px;
            text-align: center;
        }

        .header h1 {
            font-size: 20px;
            margin-bottom: 0.1rem;
        }


        .client-info {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }

        .client-info h2 {
            color: #667eea;
            margin-bottom: 1rem;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
        }

        .info-item {
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 5px;
        }

        .info-item strong {
            color: #555;
            display: block;
            margin-bottom: 0.5rem;
        }

        .section {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }

        .section h3 {
            color: #667eea;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid #667eea;
            padding-bottom: 0.5rem;
        }

        .upload-form {
            background: #f8f9fa;
            padding: 1.5rem;
            border-radius: 5px;
            margin-bottom: 2rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #555;
        }

        .form-group input,
        .form-group select {
            width: 90%;
            padding: 0.75rem;
            border: 2px solid #e1e5e9;
            border-radius: 5px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 90%);
            color: white;
            padding: 0.75rem 2rem;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: transform 0.2s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 90%);
        }

        .btn-small {
            padding: 0.5rem 1rem;
            font-size: 0.9rem;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .table th,
        .table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #e1e5e9;
        }

        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
        }

        .table tr:hover {
            background-color: #f8f9fa;
        }

        .alert {
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1.5rem;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .document-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 5px;
            margin-bottom: 1rem;
        }

        .document-info {
            flex: 1;
        }

        .document-actions {
            display: flex;
            gap: 0.5rem;
        }

        @media (max-width: 800px) {
            .nav ul {
                flex-direction: column;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .document-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
     
            <h1><strong><?php echo htmlspecialchars($client['name']); ?></strong></h1>
    
        <?php if ($message): ?>
            <div class="alert alert-success">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <!-- Client Information -->
        <div class="client-info">
            <h2>Информация за клиента</h2>
            <div class="info-grid">
                <div class="info-item">
                    <strong>Наименование:</strong>
                    <?php echo htmlspecialchars($client['name']); ?>
                    <strong>Адрес:</strong>
                    <?php echo htmlspecialchars($client['address']); ?>
                </div>
                <div class="info-item">
                    <strong>Телефон:</strong>
                    <?php echo htmlspecialchars($client['phone']); ?>
                    <strong>Имейл:</strong>
                    <?php echo htmlspecialchars($client['email']); ?>
                </div>
            </div>
            <div style="margin-top: 1rem;">
                <a href="edit_client.php?id=<?php echo $client['id']; ?>" class="btn btn-small">Редактирай данни</a>
            </div>
        </div>

        <!-- Documents Section -->
        <div class="section">
            <h3>Документи</h3>
            
            <!-- Upload Form -->
            <div class="upload-form">
                <h4>Качване на нов документ</h4>
                <form method="POST" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="document_name">Име на документа:</label>
                        <input type="text" id="document_name" name="document_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="document_type">Тип документ:</label>
                        <select id="document_type" name="document_type">
                            <option value="Договор">Договор</option>
                            <option value="Фактура">Фактура</option>
                            <option value="Удостоверение">Удостоверение</option>
                            <option value="Снимка">Снимка</option>
                            <option value="Друго">Друго</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="document">Файл:</label>
                        <input type="file" id="document" name="document" required>
                    </div>
                    
                    <button type="submit" class="btn">Качи документ</button>
                </form>
            </div>

            <!-- Documents List -->
            <?php if (empty($documents)): ?>
                <p>Няма качени документи за този клиент.</p>
            <?php else: ?>
                <?php foreach ($documents as $doc): ?>
                    <div class="document-item">
                        <div class="document-info">
                            <strong><?php echo htmlspecialchars($doc['document_name']); ?></strong>
                            <br>
                            <small>Тип: <?php echo htmlspecialchars($doc['document_type']); ?> | 
                            Качен на: <?php echo date('d.m.Y H:i', strtotime($doc['uploaded_at'])); ?></small>
                        </div>
                        <div class="document-actions">
                            <a href="<?php echo htmlspecialchars($doc['file_path']); ?>" target="_blank" class="btn btn-small">Преглед</a>
                            <a href="?id=<?php echo $client_id; ?>&delete_doc=<?php echo $doc['id']; ?>" 
                               class="btn btn-danger btn-small" 
                               onclick="return confirm('Сигурни ли сте, че искате да изтриете този документ?')">Изтрий</a>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Offers Section -->
        <div class="section">
            <h3>Оферти</h3>
            <?php if (empty($offers)): ?>
                <p>Няма оферти за този клиент.</p>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Номер</th>
                            <th>Издател</th>
                            <th>Дата</th>
                            <th>Обща сума</th>
                            <th>Действия</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($offers as $offer): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($offer['offer_number']); ?></td>
                                <td><?php echo htmlspecialchars($offer['issuer']); ?></td>
                                <td><?php echo date('d.m.Y', strtotime($offer['offer_date'])); ?></td>
                                <td><?php echo number_format($offer['total_amount'], 2); ?> лв.</td>
                                <td>
                                    <a href="view_offer.php?id=<?php echo $offer['id']; ?>" class="btn btn-small">Преглед</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <!-- Protocols Section -->
        <div class="section">
            <h3>Протоколи</h3>
            <?php if (empty($protocols)): ?>
                <p>Няма протоколи за този клиент.</p>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Изпълнител</th>
                            <th>Дата</th>
                            <th>Действия</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($protocols as $protocol): ?>
                            <tr>
                                <td><?php echo $protocol['id']; ?></td>
                                <td><?php echo htmlspecialchars($protocol['executor']); ?></td>
                                <td><?php echo date('d.m.Y', strtotime($protocol['protocol_date'])); ?></td>
                                <td>
                                    <a href="view_protocol.php?id=<?php echo $protocol['id']; ?>" class="btn btn-small">Преглед</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
		<center><button type="button" class="btn btn-danger" onclick="window.open('', '_self', ''); window.close();">Затвори</button></center>
 	
    </div>
</body>
</html>

