<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['patient_id'])) {
    header("Location: ../login.php");
    exit();
}
include '../../include/config.php';

$user_id = $_SESSION['patient_id'];
$user_name = $_SESSION['patient_name'];
$success = '';
$error = '';

// Create table if not exists
$conn->query("
    CREATE TABLE IF NOT EXISTS daily_activity_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        activity_date DATE NOT NULL,
        steps INT DEFAULT 0,
        sleep_hours DECIMAL(3,1) DEFAULT 0,
        water_intake INT DEFAULT 0,
        calories_burned INT DEFAULT 0,
        exercise_minutes INT DEFAULT 0,
        mood VARCHAR(20),
        notes TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_user_date (user_id, activity_date)
    )
");

// Get selected date
$selected_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// Get activity for selected date
$activity = null;
$result = $conn->query("
    SELECT * FROM daily_activity_logs 
    WHERE user_id = '$user_id' AND activity_date = '$selected_date'
");
if ($result && $result->num_rows > 0) {
    $activity = $result->fetch_assoc();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $activity_date = $_POST['activity_date'];
    $steps = intval($_POST['steps'] ?? 0);
    $sleep_hours = floatval($_POST['sleep_hours'] ?? 0);
    $water_intake = intval($_POST['water_intake'] ?? 0);
    $calories_burned = intval($_POST['calories_burned'] ?? 0);
    $exercise_minutes = intval($_POST['exercise_minutes'] ?? 0);
    $mood = $_POST['mood'] ?? '';
    $notes = $_POST['notes'] ?? '';
    
    $check = $conn->query("SELECT id FROM daily_activity_logs WHERE user_id = '$user_id' AND activity_date = '$activity_date'");
    
    if ($check && $check->num_rows > 0) {
        $conn->query("
            UPDATE daily_activity_logs SET 
                steps = '$steps',
                sleep_hours = '$sleep_hours',
                water_intake = '$water_intake',
                calories_burned = '$calories_burned',
                exercise_minutes = '$exercise_minutes',
                mood = '$mood',
                notes = '$notes'
            WHERE user_id = '$user_id' AND activity_date = '$activity_date'
        ");
        $success = "Activity updated successfully!";
    } else {
        $conn->query("
            INSERT INTO daily_activity_logs 
            (user_id, activity_date, steps, sleep_hours, water_intake, calories_burned, exercise_minutes, mood, notes) 
            VALUES ('$user_id', '$activity_date', '$steps', '$sleep_hours', '$water_intake', '$calories_burned', '$exercise_minutes', '$mood', '$notes')
        ");
        $success = "Activity logged successfully!";
    }
    
    // Refresh activity data
    $result = $conn->query("
        SELECT * FROM daily_activity_logs 
        WHERE user_id = '$user_id' AND activity_date = '$selected_date'
    ");
    if ($result && $result->num_rows > 0) {
        $activity = $result->fetch_assoc();
    }
}

$page_title = 'Daily Activity Tracker | UHD';
include '../../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daily Activity Tracker - UHD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: linear-gradient(135deg, #0a3d2f, #064e3b); font-family: 'Segoe UI', sans-serif; }
        
        .activity-card {
            background: white;
            border-radius: 24px;
            padding: 25px;
            margin-bottom: 25px;
            border-left: 4px solid #d4a017;
        }
        
        .stat-box {
            background: #f8f9fa;
            border-radius: 16px;
            padding: 15px;
            text-align: center;
        }
        
        .stat-number {
            font-size: 1.8rem;
            font-weight: 800;
            color: #d4a017;
        }
        
        .header-section {
            background: rgba(255,255,255,0.08);
            backdrop-filter: blur(10px);
            border-radius: 24px;
            padding: 25px;
            margin-bottom: 30px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        
        .btn-save {
            background: #d4a017;
            color: #0a3d2f;
            border: none;
            border-radius: 40px;
            padding: 12px 30px;
            font-weight: 600;
            width: 100%;
        }
        
        .btn-save:hover {
            background: #b8860b;
            color: white;
        }
        
        .back-btn {
            background: rgba(255,255,255,0.15);
            border: 1px solid rgba(255,255,255,0.2);
            color: white;
            border-radius: 40px;
            padding: 8px 20px;
            text-decoration: none;
        }
        
        .back-btn:hover {
            background: #d4a017;
            color: #0a3d2f;
        }
        
        .date-nav {
            background: white;
            border-radius: 50px;
            padding: 5px;
            display: inline-flex;
        }
        
        .date-nav a {
            padding: 8px 20px;
            border-radius: 40px;
            text-decoration: none;
            color: #0a3d2f;
        }
        
        .date-nav a.active {
            background: #d4a017;
            color: white;
        }
        
        .mood-select {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .mood-option {
            padding: 8px 15px;
            border-radius: 30px;
            cursor: pointer;
            background: #f0f0f0;
        }
        
        .mood-option.selected {
            background: #d4a017;
            color: white;
        }
        
        @media (max-width: 768px) {
            .stat-number { font-size: 1.3rem; }
        }
    </style>
</head>
<body>

<div class="container mt-4">
    <!-- Header -->
    <div class="header-section text-white">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h2 class="fw-bold mb-2"><i class="fas fa-heartbeat me-2" style="color: #d4a017;"></i> Daily Activity Tracker</h2>
                <p class="mb-0 opacity-75">Track your steps, sleep, water intake, and wellness journey.</p>
            </div>
            <div class="col-md-4 text-center mt-3 mt-md-0">
                <a href="index.php" class="back-btn"><i class="fas fa-arrow-left me-2"></i> Back to Medical Hub</a>
            </div>
        </div>
    </div>

    <!-- Date Navigation -->
    <div class="text-center mb-4">
        <div class="date-nav d-inline-flex">
            <a href="?date=<?= date('Y-m-d', strtotime($selected_date . ' -1 day')) ?>">
                <i class="fas fa-chevron-left"></i> Prev
            </a>
            <a href="?date=<?= date('Y-m-d') ?>" class="<?= $selected_date == date('Y-m-d') ? 'active' : '' ?>">
                Today
            </a>
            <a href="?date=<?= date('Y-m-d', strtotime($selected_date . ' +1 day')) ?>">
                Next <i class="fas fa-chevron-right"></i>
            </a>
        </div>
        <div class="mt-2">
            <strong class="text-white"><?= date('l, F j, Y', strtotime($selected_date)) ?></strong>
        </div>
    </div>

    <?php if($success): ?>
        <div class="alert alert-success"><?= $success ?></div>
    <?php endif; ?>

    <div class="row">
        <!-- Activity Form -->
        <div class="col-lg-7">
            <div class="activity-card">
                <h4 class="mb-3">Log Your Activity</h4>
                
                <form method="POST">
                    <input type="hidden" name="activity_date" value="<?= $selected_date ?>">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-shoe-prints me-1"></i> Steps</label>
                            <input type="number" name="steps" class="form-control" value="<?= $activity['steps'] ?? 0 ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-bed me-1"></i> Sleep (hours)</label>
                            <input type="number" step="0.5" name="sleep_hours" class="form-control" value="<?= $activity['sleep_hours'] ?? 0 ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-tint me-1"></i> Water (glasses)</label>
                            <input type="number" name="water_intake" class="form-control" value="<?= $activity['water_intake'] ?? 0 ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-fire me-1"></i> Calories Burned</label>
                            <input type="number" name="calories_burned" class="form-control" value="<?= $activity['calories_burned'] ?? 0 ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-running me-1"></i> Exercise (mins)</label>
                            <input type="number" name="exercise_minutes" class="form-control" value="<?= $activity['exercise_minutes'] ?? 0 ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-smile me-1"></i> Mood</label>
                            <select name="mood" class="form-select">
                                <option value="">Select Mood</option>
                                <option value="great" <?= ($activity['mood'] ?? '') == 'great' ? 'selected' : '' ?>>😊 Great</option>
                                <option value="good" <?= ($activity['mood'] ?? '') == 'good' ? 'selected' : '' ?>>🙂 Good</option>
                                <option value="okay" <?= ($activity['mood'] ?? '') == 'okay' ? 'selected' : '' ?>>😐 Okay</option>
                                <option value="tired" <?= ($activity['mood'] ?? '') == 'tired' ? 'selected' : '' ?>>😫 Tired</option>
                                <option value="stressed" <?= ($activity['mood'] ?? '') == 'stressed' ? 'selected' : '' ?>>😰 Stressed</option>
                            </select>
                        </div>
                        <div class="col-12 mb-3">
                            <label class="form-label fw-bold"><i class="fas fa-notes-medical me-1"></i> Notes</label>
                            <textarea name="notes" class="form-control" rows="2"><?= htmlspecialchars($activity['notes'] ?? '') ?></textarea>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn-save"><i class="fas fa-save me-2"></i> Save Activity</button>
                </form>
            </div>
        </div>
        
        <!-- Stats Summary -->
        <div class="col-lg-5">
            <div class="activity-card">
                <h5 class="mb-3">Today's Summary</h5>
                <div class="row g-2">
                    <div class="col-6">
                        <div class="stat-box">
                            <i class="fas fa-shoe-prints fa-2x mb-2"></i>
                            <div class="stat-number"><?= number_format($activity['steps'] ?? 0) ?></div>
                            <small>Steps</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="stat-box">
                            <i class="fas fa-bed fa-2x mb-2"></i>
                            <div class="stat-number"><?= $activity['sleep_hours'] ?? 0 ?></div>
                            <small>Sleep (hrs)</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="stat-box">
                            <i class="fas fa-tint fa-2x mb-2"></i>
                            <div class="stat-number"><?= $activity['water_intake'] ?? 0 ?></div>
                            <small>Water</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="stat-box">
                            <i class="fas fa-running fa-2x mb-2"></i>
                            <div class="stat-number"><?= $activity['exercise_minutes'] ?? 0 ?></div>
                            <small>Exercise</small>
                        </div>
                    </div>
                </div>
                <?php if(!empty($activity['mood'])): ?>
                    <div class="mt-3 text-center">
                        <span class="badge bg-warning text-dark p-2">Mood: <?= ucfirst($activity['mood']) ?></span>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Health Tips -->
            <div class="activity-card">
                <h5><i class="fas fa-lightbulb me-2"></i> Daily Health Tips</h5>
                <ul class="mt-2 mb-0">
                    <li>🚶‍♂️ Aim for 8,000-10,000 steps daily</li>
                    <li>💧 Drink 8 glasses of water per day</li>
                    <li>😴 Get 7-8 hours of quality sleep</li>
                    <li>🏃‍♀️ Exercise at least 30 minutes daily</li>
                </ul>
            </div>
        </div>
    </div>
</div>

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