<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Includes/helpers.php';
use HatiApp\Core\Database;

$db = new Database();
$conn = $db->getConnection();
$project = null;
$tasks = [];
$project_files = [];
$users = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
$project_id = $_GET['id'] ?? 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add_task') {
        $task_name = $_POST['task_name'] ?? '';
        $assigned_to_user_name = $_POST['assigned_to_user_name'] ?? null;
        $due_date = $_POST['due_date'] ?? null;
        $priority = $_POST['priority'] ?? 'medium';
        $is_extra_task = isset($_POST['is_extra_task']) ? 1 : 0;
        $extra_fee = $is_extra_task ? ($_POST['extra_fee'] ?? 0) : 0;

        try {
            $conn->beginTransaction();
            $stmt = $conn->prepare("INSERT INTO project_tasks (project_id, task_name, due_date, assigned_to_user_name, priority, is_extra_task, extra_fee) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$project_id, $task_name, $due_date, $assigned_to_user_name, $priority, $is_extra_task, $extra_fee]);
            
            if ($is_extra_task && $extra_fee > 0) {
                $stmt_update_project = $conn->prepare("UPDATE projects SET price = price + ? WHERE id = ?");
                $stmt_update_project->execute([$extra_fee, $project_id]);
            }
            
            $conn->commit();
            header("Location: view_project.php?id=$project_id&status=success&message=" . urlencode('Yeni görev başarıyla eklendi!'));
            exit;
        } catch (PDOException $e) {
            $conn->rollBack();
            $message = 'Hata: Görev eklenirken bir sorun oluştu. ' . $e->getMessage();
            $message_type = 'error';
            header("Location: view_project.php?id=$project_id&status=error&message=" . urlencode($message));
            exit;
        }
    } elseif ($_POST['action'] === 'upload_file') {
        if (isset($_FILES['project_file']) && $_FILES['project_file']['error'] === UPLOAD_ERR_OK) {
            $file_name = $_FILES['project_file']['name'];
            $file_tmp_name = $_FILES['project_file']['tmp_name'];
            $file_size = $_FILES['project_file']['size'];
            $upload_dir = __DIR__ . '/uploads/projects/';
            $unique_file_name = uniqid() . '-' . basename($file_name);
            $destination = $upload_dir . $unique_file_name;
            if (move_uploaded_file($file_tmp_name, $destination)) {
                try {
                    $stmt = $conn->prepare("INSERT INTO project_files (project_id, file_name, file_path, file_size) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$project_id, $file_name, $destination, $file_size]);
                    header("Location: view_project.php?id=$project_id&status=success&message=" . urlencode('Dosya başarıyla yüklendi!'));
                    exit;
                } catch (PDOException $e) {
                    $message = 'Veritabanı hatası: ' . $e->getMessage();
                    $message_type = 'error';
                }
            } else {
                $message = 'Dosya yüklenirken bir hata oluştu.';
                $message_type = 'error';
            }
        } else {
            $message = 'Lütfen geçerli bir dosya seçin.';
            $message_type = 'error';
        }
    } elseif ($_POST['action'] === 'update_status') {
        $new_status = $_POST['status'] ?? '';
        $completion_percentage = $_POST['completion_percentage'] ?? 0;
        try {
            $stmt = $conn->prepare("UPDATE projects SET status = ?, completion_percentage = ? WHERE id = ?");
            $stmt->execute([$new_status, $completion_percentage, $project_id]);
            header("Location: view_project.php?id=$project_id&status=success&message=" . urlencode('Proje durumu başarıyla güncellendi!'));
            exit;
        } catch (PDOException $e) {
            $message = 'Hata: Proje durumu güncellenirken bir sorun oluştu. ' . $e->getMessage();
            $message_type = 'error';
            header("Location: view_project.php?id=$project_id&status=error&message=" . urlencode($message));
            exit;
        }
    } elseif ($_POST['action'] === 'update_finance') {
        $new_price = $_POST['price'] ?? 0;
        $new_expenses = $_POST['total_expenses'] ?? 0;
        $remaining_balance = $new_price - $new_expenses;
        try {
            $stmt = $conn->prepare("UPDATE projects SET price = ?, total_expenses = ?, remaining_balance = ? WHERE id = ?");
            $stmt->execute([$new_price, $new_expenses, $remaining_balance, $project_id]);
            header("Location: view_project.php?id=$project_id&status=success&message=" . urlencode('Finansal bilgiler başarıyla güncellendi!'));
            exit;
        } catch (PDOException $e) {
            $message = 'Hata: Finansal bilgiler güncellenirken bir sorun oluştu. ' . $e->getMessage();
            $message_type = 'error';
            header("Location: view_project.php?id=$project_id&status=error&message=" . urlencode($message));
            exit;
        }
    } elseif ($_POST['action'] === 'update_task_status') {
        $task_id = $_POST['task_id'] ?? 0;
        $new_task_status = $_POST['new_task_status'] ?? '';
        if ($task_id > 0 && !empty($new_task_status)) {
            try {
                $stmt = $conn->prepare("UPDATE project_tasks SET status = ? WHERE id = ?");
                $stmt->execute([$new_task_status, $task_id]);
                header("Location: view_project.php?id=$project_id&status=success&message=" . urlencode('Görev durumu güncellendi.'));
                exit;
            } catch (PDOException $e) {
                $message = 'Hata: Görev durumu güncellenirken bir sorun oluştu. ' . $e->getMessage();
                $message_type = 'error';
                header("Location: view_project.php?id=$project_id&status=error&message=" . urlencode($message));
                exit;
            }
        }
    }
}
if ($project_id > 0) {
    try {
        $stmt_project = $conn->prepare("SELECT p.*, u.name as assigned_user_name FROM projects p LEFT JOIN users u ON p.assigned_to_user_id = u.id WHERE p.id = ?");
        $stmt_project->execute([$project_id]);
        $project = $stmt_project->fetch(PDO::FETCH_ASSOC);
        
        $stmt_tasks = $conn->prepare("SELECT pt.* FROM project_tasks pt WHERE pt.project_id = ? ORDER BY pt.due_date ASC, pt.is_extra_task DESC");
        $stmt_tasks->execute([$project_id]);
        $tasks = $stmt_tasks->fetchAll(PDO::FETCH_ASSOC);

        $stmt_files = $conn->prepare("SELECT * FROM project_files WHERE project_id = ? ORDER BY upload_date DESC");
        $stmt_files->execute([$project_id]);
        $project_files = $stmt_files->fetchAll(PDO::FETCH_ASSOC);

        $stmt_users = $conn->prepare("SELECT id, name FROM users ORDER BY name ASC");
        $stmt_users->execute();
        $users = $stmt_users->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $message = 'Hata: ' . $e->getMessage();
        $message_type = 'error';
    }
}
if (!$project) {
    echo "Hata: Proje bulunamadı.";
    exit;
}

$project_address_for_map = urlencode($project['address'] . ', ' . $project['city'] . ', ' . $project['country']);
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Proje Detayı: <?php echo htmlspecialchars($project['project_name']); ?></title>
    <link rel="stylesheet" href="css/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<div class="project-detail-container">
    <div class="project-main-details">
        <div class="detail-box">
            <h3 class="detail-box-title">Proje Bilgileri</h3>
            <div class="detail-box-grid">
                <div class="project-info-grid">
                    <div><strong>Proje Adı:</strong> <?php echo htmlspecialchars($project['project_name']); ?></div>
                    <div><strong>Müteahhit Firma:</strong> <?php echo htmlspecialchars($project['contractor_company'] ?? '-'); ?></div>
                    <div><strong>Başlangıç Tarihi:</strong> <?php echo htmlspecialchars($project['start_date']); ?></div>
                    <div><strong>Bitiş Tarihi:</strong> <?php echo htmlspecialchars($project['end_date'] ?? '-'); ?></div>
                    <div><strong>Toplam Fiyat:</strong> <?php echo htmlspecialchars(number_format($project['price'], 2, ',', '.') ?? '0,00'); ?> TL</div>
                    <div><strong>Toplam Gider:</strong> <?php echo htmlspecialchars(number_format($project['total_expenses'], 2, ',', '.') ?? '0,00'); ?> TL</div>
                    <div><strong>Bağımsız Bölüm Sayısı:</strong> <?php echo htmlspecialchars($project['number_of_independent_units'] ?? '-'); ?></div>
                    <div><strong>Toplam İnşaat Alanı:</strong> <?php echo htmlspecialchars($project['total_construction_area'] ?? '-'); ?> m²</div>
                    <div class="full-width"><strong>Açıklama:</strong> <?php echo nl2br(htmlspecialchars($project['description'] ?? '-')); ?></div>
                </div>
                <div class="map-container">
                    <?php if ($project['address'] ?? ''): ?>
                        <iframe
                            width="100%"
                            height="100%"
                            frameborder="0" style="border:0"
                            src="https://maps.google.com/maps?q=<?php echo $project_address_for_map; ?>&hl=tr&z=14&t=&output=embed"
                            allowfullscreen>
                        </iframe>
                    <?php else: ?>
                        <p>Harita için adres bilgisi bulunmamaktadır.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="detail-box-grid">
            <div class="detail-box">
                <h3 class="detail-box-title">İş Ekle</h3>
                <div class="task-form-container">
                    <form id="add-task-form" action="view_project.php?id=<?php echo $project['id']; ?>" method="POST">
                        <input type="hidden" name="action" value="add_task">
                        <div class="form-group">
                            <label for="task_name">İş Tanımı:</label>
                            <input type="text" id="task_name" name="task_name" required>
                        </div>
                        <div class="task-form-grid">
                            <div class="form-group">
                                <label for="assigned_to_user_name">Atanan Kişi:</label>
                                <input type="text" id="assigned_to_user_name" name="assigned_to_user_name">
                            </div>
                            <div class="form-group">
                                <label for="due_date">Son Tarih:</label>
                                <input type="date" id="due_date" name="due_date">
                            </div>
                        </div>
                        <div class="task-form-grid">
                            <div class="form-group">
                                <label for="priority">Öncelik:</label>
                                <select id="priority" name="priority">
                                    <option value="low">Düşük</option>
                                    <option value="medium" selected>Orta</option>
                                    <option value="high">Yüksek</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="is_extra_task">
                                    <input type="checkbox" id="is_extra_task" name="is_extra_task" value="1"> Ek İş
                                </label>
                                <div class="extra-fee-field" id="extra_fee_container" style="display: none;">
                                    <label for="extra_fee">Ek Ücret:</label>
                                    <input type="number" id="extra_fee" name="extra_fee" step="0.01" min="0">
                                </div>
                            </div>
                        </div>
                        <button type="submit">İş Ekle</button>
                    </form>
                </div>
            </div>
            <div class="detail-box">
                <h3 class="detail-box-title">Finansal Durum</h3>
                <div class="finance-grid">
                    <div><strong>Toplam Bakiye:</strong> <?php echo number_format($project['price'] ?? 0, 2, ',', '.') ?? '0,00'; ?> TL</div>
                    <div><strong>Harcanan Bakiye:</strong> <?php echo number_format($project['total_expenses'] ?? 0, 2, ',', '.') ?? '0,00'; ?> TL</div>
                    <div><strong>Kalan Bakiye:</strong> <?php echo number_format(($project['price'] - $project['total_expenses']) ?? 0, 2, ',', '.') ?? '0,00'; ?> TL</div>
                </div>
                <?php if ($_SESSION['user_role'] === 'admin'): ?>
                    <hr>
                    <form action="view_project.php?id=<?php echo $project['id']; ?>" method="POST" class="update-finance-form">
                        <input type="hidden" name="action" value="update_finance">
                        <div class="form-group">
                            <label for="price">Toplam Bakiye:</label>
                            <input type="number" id="price" name="price" step="0.01" min="0" value="<?php echo htmlspecialchars($project['price'] ?? 0); ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="total_expenses">Harcanan Bakiye:</label>
                            <input type="number" id="total_expenses" name="total_expenses" step="0.01" min="0" value="<?php echo htmlspecialchars($project['total_expenses'] ?? 0); ?>" required>
                        </div>
                        <button type="submit">Güncelle</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="detail-box full-width-box">
            <h3 class="detail-box-title">Yapılan ve Ek İşlerin Listesi</h3>
            <?php if (empty($tasks)): ?>
                <p>Bu projeye ait bir görev bulunmamaktadır.</p>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>İş Tanımı</th>
                            <th>Türü</th>
                            <th>Ek Ücret</th>
                            <th>Atanan</th>
                            <th>Son Tarih</th>
                            <th>Durum</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($tasks as $task): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($task['task_name']); ?></td>
                                <td><?php echo $task['is_extra_task'] ? 'Ek İş' : 'Normal'; ?></td>
                                <td><?php echo $task['is_extra_task'] ? htmlspecialchars(number_format($task['extra_fee'], 2, ',', '.') . ' TL') : '-'; ?></td>
                                <td><?php echo htmlspecialchars($task['assigned_to_user_name'] ?? '-'); ?></td>
                                <td><?php echo htmlspecialchars($task['due_date'] ?? '-'); ?></td>
                                <td>
                                    <form action="view_project.php?id=<?php echo $project['id']; ?>" method="POST" class="inline-form">
                                        <input type="hidden" name="action" value="update_task_status">
                                        <input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
                                        <select name="new_task_status" onchange="this.form.submit()">
                                            <option value="todo" <?php echo $task['status'] === 'todo' ? 'selected' : ''; ?>>Yapılacak</option>
                                            <option value="in_progress" <?php echo $task['status'] === 'in_progress' ? 'selected' : ''; ?>>Devam Ediyor</option>
                                            <option value="completed" <?php echo $task['status'] === 'completed' ? 'selected' : ''; ?>>Tamamlandı</option>
                                        </select>
                                    </form>
                                </td>
                                <td>
                                    <a href="delete.php?table=project_tasks&id=<?php echo $task['id']; ?>&redirect=view_project.php?id=<?php echo $project['id']; ?>" onclick="return confirm('Bu görevi silmek istediğinizden emin misiniz?');">Sil</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        
        <div class="detail-box full-width-box">
            <h3 class="detail-box-title">Çizimler ve Dosyalar</h3>
            <form action="view_project.php?id=<?php echo $project['id']; ?>" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload_file">
                <div class="form-group">
                    <label for="project_file">Dosya Seç:</label>
                    <input type="file" id="project_file" name="project_file" required>
                </div>
                <button type="submit">Dosya Yükle</button>
            </form>
            <hr>
            <h3>Yüklü Dosyaların Listesi</h3>
            <?php if (empty($project_files)): ?>
                <p>Bu projeye ait yüklü bir dosya bulunmamaktadır.</p>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Dosya Adı</th>
                            <th>Boyut</th>
                            <th>Yükleme Tarihi</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($project_files as $file): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($file['file_name']); ?></td>
                                <td><?php echo round($file['file_size'] / 1024, 2); ?> KB</td>
                                <td><?php echo date('d.m.Y H:i', strtotime($file['upload_date'])); ?></td>
                                <td>
                                    <a href="download.php?file_id=<?php echo $file['id']; ?>">İndir</a> |
                                    <a href="delete.php?table=project_files&id=<?php echo $file['id']; ?>&redirect=view_project.php?id=<?php echo $project['id']; ?>" onclick="return confirm('Bu dosyayı silmek istediğinizden emin misiniz?');">Sil</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</div>
</main>
<script>
    document.getElementById('is_extra_task').addEventListener('change', function() {
        const extraFeeContainer = document.getElementById('extra_fee_container');
        if (this.checked) {
            extraFeeContainer.style.display = 'block';
            document.getElementById('extra_fee').setAttribute('required', 'required');
        } else {
            extraFeeContainer.style.display = 'none';
            document.getElementById('extra_fee').removeAttribute('required');
        }
    });
</script>
</body>
</html>