<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

/* ════════════════════════════════════════════════════════
   EXPORT HANDLER  ─  GET ?export=TYPE&format=FORMAT
════════════════════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['export'])) {
    $type   = $_GET['export'] ?? 'all';   // all | sessions | subjects | tasks | goals
    $format = $_GET['format'] ?? 'json';  // json | csv

    $allowed_types   = ['all','sessions','subjects','tasks','goals'];
    $allowed_formats = ['json','csv'];
    if (!in_array($type,$allowed_types))   die('Invalid type');
    if (!in_array($format,$allowed_formats)) die('Invalid format');

    /* ── fetch data ── */
    $data = [];

    // Subjects (always needed as reference)
    $subQ = $pdo->prepare("SELECT id,name,color,target_marks,created_at FROM subjects WHERE user_id=? ORDER BY name");
    $subQ->execute([$uid]); $subjects = $subQ->fetchAll(PDO::FETCH_ASSOC);

    if ($type === 'all' || $type === 'subjects') {
        // include marks inside subjects
        foreach ($subjects as &$s) {
            $mQ = $pdo->prepare("SELECT exam_name,marks_obtained,total_marks,exam_date,notes FROM marks WHERE user_id=? AND subject_id=? ORDER BY exam_date");
            $mQ->execute([$uid,$s['id']]); $s['marks'] = $mQ->fetchAll(PDO::FETCH_ASSOC);
        }
        unset($s);
        $data['subjects'] = $subjects;
    }

    if ($type === 'all' || $type === 'sessions') {
        // Build subject name map
        $subMap = array_column($subjects, 'name', 'id');
        $ssQ = $pdo->prepare("SELECT ss.date,ss.duration_minutes,ss.notes,s.name as subject_name FROM study_sessions ss JOIN subjects s ON ss.subject_id=s.id WHERE ss.user_id=? ORDER BY ss.date DESC,ss.created_at DESC");
        $ssQ->execute([$uid]); $sessions = $ssQ->fetchAll(PDO::FETCH_ASSOC);
        $data['study_sessions'] = $sessions;
    }

    if ($type === 'all' || $type === 'tasks') {
        $tQ = $pdo->prepare("SELECT t.title,t.description,t.due_date,t.priority,t.status,s.name as subject_name FROM tasks t LEFT JOIN subjects s ON t.subject_id=s.id WHERE t.user_id=? ORDER BY t.due_date,t.priority DESC");
        $tQ->execute([$uid]); $data['tasks'] = $tQ->fetchAll(PDO::FETCH_ASSOC);
    }

    if ($type === 'all' || $type === 'goals') {
        $gQ = $pdo->prepare("SELECT g.title,g.type,g.target_value,g.current_value,g.unit,g.deadline,g.status,s.name as subject_name FROM goals g LEFT JOIN subjects s ON g.subject_id=s.id WHERE g.user_id=? ORDER BY g.created_at DESC");
        $gQ->execute([$uid]); $data['goals'] = $gQ->fetchAll(PDO::FETCH_ASSOC);
    }

    $username = preg_replace('/[^a-z0-9]/i','_', $_SESSION['user_name'] ?? 'user');
    $date     = date('Y-m-d');
    $filename = "studytrack_{$username}_{$type}_{$date}";

    /* ── JSON export ── */
    if ($format === 'json') {
        $export = [
            '_meta' => [
                'app'        => 'StudyTrack',
                'version'    => '1.0',
                'exported_at'=> date('Y-m-d H:i:s'),
                'exported_by'=> $_SESSION['user_name'],
                'type'       => $type,
            ],
            'data' => $data
        ];
        header('Content-Type: application/json');
        header("Content-Disposition: attachment; filename=\"{$filename}.json\"");
        header('Cache-Control: no-cache');
        echo json_encode($export, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }

    /* ── CSV export ── */
    if ($format === 'csv') {
        header('Content-Type: text/csv; charset=UTF-8');
        header("Content-Disposition: attachment; filename=\"{$filename}.csv\"");
        header('Cache-Control: no-cache');
        // BOM for Excel UTF-8
        echo "\xEF\xBB\xBF";
        $out = fopen('php://output','w');

        if ($type === 'sessions' || $type === 'all') {
            if ($type === 'all') fputcsv($out, ['=== STUDY SESSIONS ===']);
            fputcsv($out, ['Date','Subject','Duration (min)','Notes']);
            foreach ($data['study_sessions'] ?? [] as $r)
                fputcsv($out, [$r['date'],$r['subject_name'],$r['duration_minutes'],$r['notes']]);
            if ($type === 'all') fputcsv($out, []);
        }

        if ($type === 'subjects' || $type === 'all') {
            if ($type === 'all') fputcsv($out, ['=== SUBJECTS & MARKS ===']);
            fputcsv($out, ['Subject','Color','Target Marks','Exam Name','Marks Obtained','Total Marks','Exam Date','Notes']);
            foreach ($data['subjects'] ?? [] as $s) {
                if (empty($s['marks'])) {
                    fputcsv($out, [$s['name'],$s['color'],$s['target_marks'],'','','','','']);
                } else {
                    foreach ($s['marks'] as $m)
                        fputcsv($out, [$s['name'],$s['color'],$s['target_marks'],$m['exam_name'],$m['marks_obtained'],$m['total_marks'],$m['exam_date'],$m['notes']]);
                }
            }
            if ($type === 'all') fputcsv($out, []);
        }

        if ($type === 'tasks' || $type === 'all') {
            if ($type === 'all') fputcsv($out, ['=== TASKS ===']);
            fputcsv($out, ['Title','Description','Due Date','Priority','Status','Subject']);
            foreach ($data['tasks'] ?? [] as $r)
                fputcsv($out, [$r['title'],$r['description'],$r['due_date'],$r['priority'],$r['status'],$r['subject_name']]);
            if ($type === 'all') fputcsv($out, []);
        }

        if ($type === 'goals' || $type === 'all') {
            if ($type === 'all') fputcsv($out, ['=== GOALS ===']);
            fputcsv($out, ['Title','Type','Target','Current','Unit','Deadline','Status','Subject']);
            foreach ($data['goals'] ?? [] as $r)
                fputcsv($out, [$r['title'],$r['type'],$r['target_value'],$r['current_value'],$r['unit'],$r['deadline'],$r['status'],$r['subject_name']]);
        }

        fclose($out); exit;
    }
}

/* ════════════════════════════════════════════════════════
   IMPORT HANDLER  ─  POST (JSON file upload)
════════════════════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');

    $action = $_POST['action'] ?? '';

    /* ── Parse uploaded JSON ── */
    if ($action === 'import') {
        if (empty($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK)
            echo json_encode(['success'=>false,'message'=>'No file uploaded.']) and exit;

        $raw = file_get_contents($_FILES['import_file']['tmp_name']);
        $json = json_decode($raw, true);
        if (!$json || !isset($json['_meta'],$json['data']))
            echo json_encode(['success'=>false,'message'=>'Invalid StudyTrack backup file.']) and exit;

        $importData = $json['data'];
        $mode = $_POST['mode'] ?? 'merge'; // merge | replace
        $sections = json_decode($_POST['sections'] ?? '[]', true);

        $stats = ['subjects'=>0,'marks'=>0,'sessions'=>0,'tasks'=>0,'goals'=>0,'skipped'=>0];

        try {
            $pdo->beginTransaction();

            /* -- REPLACE mode: delete existing data first -- */
            if ($mode === 'replace') {
                if (in_array('subjects', $sections)) {
                    $pdo->prepare("DELETE FROM marks WHERE user_id=?")->execute([$uid]);
                    $pdo->prepare("DELETE FROM study_sessions WHERE user_id=?")->execute([$uid]);
                    $pdo->prepare("DELETE FROM subjects WHERE user_id=?")->execute([$uid]);
                }
                if (in_array('tasks', $sections))
                    $pdo->prepare("DELETE FROM tasks WHERE user_id=?")->execute([$uid]);
                if (in_array('goals', $sections))
                    $pdo->prepare("DELETE FROM goals WHERE user_id=?")->execute([$uid]);
                if (in_array('sessions', $sections) && !in_array('subjects',$sections))
                    $pdo->prepare("DELETE FROM study_sessions WHERE user_id=?")->execute([$uid]);
            }

            /* -- Subjects & Marks -- */
            if (in_array('subjects', $sections) && !empty($importData['subjects'])) {
                foreach ($importData['subjects'] as $s) {
                    $name  = substr(trim($s['name'] ?? ''), 0, 100);
                    $color = $s['color'] ?? '#6366f1';
                    $tgt   = is_numeric($s['target_marks'] ?? null) ? (float)$s['target_marks'] : 100;
                    if (!$name) { $stats['skipped']++; continue; }

                    // Find or create subject
                    $ex = $pdo->prepare("SELECT id FROM subjects WHERE user_id=? AND name=?");
                    $ex->execute([$uid,$name]); $existing = $ex->fetchColumn();

                    if ($existing) {
                        $subId = $existing;
                    } else {
                        $pdo->prepare("INSERT INTO subjects (user_id,name,color,target_marks) VALUES (?,?,?,?)")
                            ->execute([$uid,$name,$color,$tgt]);
                        $subId = $pdo->lastInsertId();
                        $stats['subjects']++;
                    }

                    // Marks inside subject
                    foreach ($s['marks'] ?? [] as $m) {
                        $eName = substr(trim($m['exam_name'] ?? ''), 0, 150);
                        $eDate = $m['exam_date'] ?? null;
                        if (!$eName || !$eDate) { $stats['skipped']++; continue; }
                        // Skip duplicate
                        $dup = $pdo->prepare("SELECT id FROM marks WHERE user_id=? AND subject_id=? AND exam_name=? AND exam_date=?");
                        $dup->execute([$uid,$subId,$eName,$eDate]);
                        if ($dup->fetch()) { $stats['skipped']++; continue; }
                        $pdo->prepare("INSERT INTO marks (user_id,subject_id,exam_name,marks_obtained,total_marks,exam_date,notes) VALUES (?,?,?,?,?,?,?)")
                            ->execute([$uid,$subId,$eName,(float)($m['marks_obtained']??0),(float)($m['total_marks']??100),$eDate,$m['notes']??null]);
                        $stats['marks']++;
                    }
                }
            }

            /* -- Study Sessions -- */
            if (in_array('sessions', $sections) && !empty($importData['study_sessions'])) {
                // Build subject name→id map
                $mapQ = $pdo->prepare("SELECT name,id FROM subjects WHERE user_id=?");
                $mapQ->execute([$uid]); $subMap = $mapQ->fetchAll(PDO::FETCH_KEY_PAIR);

                foreach ($importData['study_sessions'] as $ss) {
                    $sName = trim($ss['subject_name'] ?? '');
                    $date  = $ss['date'] ?? null;
                    $dur   = (int)($ss['duration_minutes'] ?? 0);
                    if (!$sName || !$date || $dur <= 0) { $stats['skipped']++; continue; }

                    // Auto-create subject if not found
                    if (!isset($subMap[$sName])) {
                        $pdo->prepare("INSERT INTO subjects (user_id,name) VALUES (?,?)")->execute([$uid,$sName]);
                        $subMap[$sName] = $pdo->lastInsertId();
                        $stats['subjects']++;
                    }
                    $subId = $subMap[$sName];

                    // Skip duplicate (same user+subject+date+duration)
                    $dup = $pdo->prepare("SELECT id FROM study_sessions WHERE user_id=? AND subject_id=? AND date=? AND duration_minutes=?");
                    $dup->execute([$uid,$subId,$date,$dur]);
                    if ($dup->fetch()) { $stats['skipped']++; continue; }

                    $pdo->prepare("INSERT INTO study_sessions (user_id,subject_id,date,duration_minutes,notes) VALUES (?,?,?,?,?)")
                        ->execute([$uid,$subId,$date,$dur,$ss['notes']??null]);
                    $stats['sessions']++;
                }
            }

            /* -- Tasks -- */
            if (in_array('tasks', $sections) && !empty($importData['tasks'])) {
                $mapQ = $pdo->prepare("SELECT name,id FROM subjects WHERE user_id=?");
                $mapQ->execute([$uid]); $subMap = $mapQ->fetchAll(PDO::FETCH_KEY_PAIR);

                $validPri = ['low','medium','high'];
                $validSta = ['pending','in_progress','completed'];
                foreach ($importData['tasks'] as $t) {
                    $title = substr(trim($t['title'] ?? ''), 0, 255);
                    if (!$title) { $stats['skipped']++; continue; }
                    $pri = in_array($t['priority']??'',$validPri) ? $t['priority'] : 'medium';
                    $sta = in_array($t['status']??'',$validSta) ? $t['status'] : 'pending';
                    $subId = null;
                    if (!empty($t['subject_name']) && isset($subMap[$t['subject_name']]))
                        $subId = $subMap[$t['subject_name']];
                    $pdo->prepare("INSERT INTO tasks (user_id,subject_id,title,description,due_date,priority,status) VALUES (?,?,?,?,?,?,?)")
                        ->execute([$uid,$subId,$title,$t['description']??null,$t['due_date']??null,$pri,$sta]);
                    $stats['tasks']++;
                }
            }

            /* -- Goals -- */
            if (in_array('goals', $sections) && !empty($importData['goals'])) {
                $mapQ = $pdo->prepare("SELECT name,id FROM subjects WHERE user_id=?");
                $mapQ->execute([$uid]); $subMap = $mapQ->fetchAll(PDO::FETCH_KEY_PAIR);

                $validTypes = ['study_hours','mark_target','streak','custom'];
                $validSta   = ['active','completed','failed'];
                foreach ($importData['goals'] as $g) {
                    $title = substr(trim($g['title'] ?? ''), 0, 200);
                    if (!$title) { $stats['skipped']++; continue; }
                    $type = in_array($g['type']??'',$validTypes) ? $g['type'] : 'custom';
                    $sta  = in_array($g['status']??'',$validSta)  ? $g['status'] : 'active';
                    $subId = null;
                    if (!empty($g['subject_name']) && isset($subMap[$g['subject_name']]))
                        $subId = $subMap[$g['subject_name']];
                    $pdo->prepare("INSERT INTO goals (user_id,subject_id,title,type,target_value,current_value,unit,deadline,status) VALUES (?,?,?,?,?,?,?,?,?)")
                        ->execute([$uid,$subId,$title,$type,(float)($g['target_value']??0),(float)($g['current_value']??0),$g['unit']??'',$g['deadline']??null,$sta]);
                    $stats['goals']++;
                }
            }

            $pdo->commit();
            echo json_encode(['success'=>true,'stats'=>$stats]);

        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success'=>false,'message'=>'Import failed: '.$e->getMessage()]);
        }
        exit;
    }
}

/* ════════════════════════════════════════════════════════
   PAGE RENDER
════════════════════════════════════════════════════════ */
// Count current data
$counts = [];
$counts['subjects'] = $pdo->prepare("SELECT COUNT(*) FROM subjects WHERE user_id=?");
$counts['subjects']->execute([$uid]); $counts['subjects'] = (int)$counts['subjects']->fetchColumn();

$counts['sessions'] = $pdo->prepare("SELECT COUNT(*) FROM study_sessions WHERE user_id=?");
$counts['sessions']->execute([$uid]); $counts['sessions'] = (int)$counts['sessions']->fetchColumn();

$counts['marks'] = $pdo->prepare("SELECT COUNT(*) FROM marks WHERE user_id=?");
$counts['marks']->execute([$uid]); $counts['marks'] = (int)$counts['marks']->fetchColumn();

$counts['tasks'] = $pdo->prepare("SELECT COUNT(*) FROM tasks WHERE user_id=?");
$counts['tasks']->execute([$uid]); $counts['tasks'] = (int)$counts['tasks']->fetchColumn();

$counts['goals'] = $pdo->prepare("SELECT COUNT(*) FROM goals WHERE user_id=?");
$counts['goals']->execute([$uid]); $counts['goals'] = (int)$counts['goals']->fetchColumn();

require_once 'includes/header.php';
renderHeader('Data Export & Import', 'settings');
?>

<style>
/* ══ Page layout ══ */
.dei-grid { display:grid; grid-template-columns:1fr 1fr; gap:20px; }
@media(max-width:768px){ .dei-grid{grid-template-columns:1fr;} }

/* ══ Section cards ══ */
.dei-card {
  background:var(--bg-secondary,rgba(255,255,255,.04));
  border:1px solid var(--border);
  border-radius:16px; padding:24px;
}
.dei-card-title {
  font-size:16px; font-weight:800; color:var(--text-primary);
  font-family:'Sora',sans-serif;
  display:flex; align-items:center; gap:8px; margin-bottom:4px;
}
.dei-card-sub { font-size:12px; color:var(--text-muted); margin-bottom:20px; }

/* ══ Stats strip ══ */
.dei-stats { display:flex; flex-wrap:wrap; gap:10px; margin-bottom:24px; }
.dei-stat {
  flex:1; min-width:80px; text-align:center;
  background:rgba(99,102,241,.08); border:1px solid rgba(99,102,241,.18);
  border-radius:12px; padding:12px 8px;
}
.dei-stat-n { font-size:22px; font-weight:800; color:#818cf8; font-family:'Sora',sans-serif; }
.dei-stat-l { font-size:10px; color:var(--text-muted); margin-top:2px; text-transform:uppercase; letter-spacing:.5px; font-weight:600; }

/* ══ Format selector ══ */
.format-row { display:flex; gap:8px; margin-bottom:16px; flex-wrap:wrap; }
.fmt-btn {
  flex:1; min-width:100px; padding:10px; border-radius:10px; border:1px solid var(--border);
  background:transparent; color:var(--text-muted); font-size:13px; font-weight:600;
  cursor:pointer; transition:all .2s; text-align:center;
}
.fmt-btn.active { background:rgba(99,102,241,.15); border-color:rgba(99,102,241,.45); color:#818cf8; }
.fmt-btn:hover:not(.active) { border-color:rgba(255,255,255,.18); color:var(--text-primary); }

/* ══ Export type checkboxes ══ */
.exp-checks { display:flex; flex-direction:column; gap:8px; margin-bottom:20px; }
.exp-check-row {
  display:flex; align-items:center; gap:10px; padding:10px 14px;
  border-radius:10px; border:1px solid var(--border);
  cursor:pointer; transition:border-color .2s, background .2s;
  user-select:none;
}
.exp-check-row:hover { border-color:rgba(99,102,241,.35); background:rgba(99,102,241,.05); }
.exp-check-row.checked { border-color:rgba(99,102,241,.45); background:rgba(99,102,241,.08); }
.exp-check-row input[type=checkbox] { width:16px; height:16px; accent-color:#6366f1; cursor:pointer; }
.exp-check-icon { font-size:18px; }
.exp-check-label { flex:1; }
.exp-check-label strong { display:block; font-size:13px; font-weight:700; color:var(--text-primary); }
.exp-check-label span { font-size:11px; color:var(--text-muted); }
.exp-check-count { font-size:12px; font-weight:700; color:#818cf8; background:rgba(99,102,241,.12); padding:2px 9px; border-radius:99px; }

/* ══ Import mode tabs ══ */
.mode-row { display:flex; gap:8px; margin-bottom:16px; }
.mode-btn {
  flex:1; padding:10px; border-radius:10px; border:1px solid var(--border);
  background:transparent; color:var(--text-muted); font-size:13px; font-weight:600;
  cursor:pointer; transition:all .2s; text-align:center;
}
.mode-btn.active { background:rgba(99,102,241,.15); border-color:rgba(99,102,241,.45); color:#818cf8; }

/* ══ File drop zone ══ */
.drop-zone {
  border:2px dashed rgba(99,102,241,.35); border-radius:14px; padding:36px 24px;
  text-align:center; cursor:pointer; transition:border-color .2s, background .2s;
  margin-bottom:16px; position:relative;
}
.drop-zone:hover,.drop-zone.drag { border-color:#6366f1; background:rgba(99,102,241,.06); }
.drop-zone input[type=file] { position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%; }
.drop-icon { font-size:36px; margin-bottom:10px; }
.drop-text { font-size:14px; font-weight:700; color:var(--text-primary); margin-bottom:4px; }
.drop-sub  { font-size:12px; color:var(--text-muted); }
.drop-file-name { font-size:13px; font-weight:700; color:#818cf8; margin-top:8px; display:none; }

/* ══ Progress/Result ══ */
.dei-result {
  display:none; padding:16px; border-radius:12px; margin-top:14px;
  border:1px solid; font-size:13px;
}
.dei-result.success { background:rgba(16,185,129,.08); border-color:rgba(16,185,129,.3); color:#34d399; }
.dei-result.error   { background:rgba(239,68,68,.08);  border-color:rgba(239,68,68,.3);  color:#f87171; }
.dei-result-title { font-weight:800; margin-bottom:6px; font-size:14px; }
.dei-result-stat-row { display:flex; flex-wrap:wrap; gap:8px; margin-top:10px; }
.dei-result-stat { background:rgba(255,255,255,.07); border-radius:8px; padding:6px 12px; }
.dei-result-stat strong { display:block; font-size:16px; font-weight:800; color:#fff; }
.dei-result-stat span { font-size:10px; color:rgba(255,255,255,.5); text-transform:uppercase; }

/* ══ Buttons ══ */
.btn-export, .btn-import {
  width:100%; padding:12px; border-radius:12px; font-size:14px; font-weight:700;
  cursor:pointer; border:none; transition:all .2s;
  display:flex; align-items:center; justify-content:center; gap:8px;
}
.btn-export { background:linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff; box-shadow:0 4px 14px rgba(99,102,241,.35); }
.btn-export:hover { transform:translateY(-2px); box-shadow:0 8px 20px rgba(99,102,241,.4); }
.btn-import { background:linear-gradient(135deg,#0ea5e9,#6366f1); color:#fff; box-shadow:0 4px 14px rgba(14,165,233,.3); }
.btn-import:hover { transform:translateY(-2px); box-shadow:0 8px 20px rgba(14,165,233,.35); }
.btn-export:disabled,.btn-import:disabled { opacity:.5; cursor:not-allowed; transform:none; }

/* ══ Warning box ══ */
.dei-warn {
  display:flex; gap:10px; padding:12px 14px; border-radius:10px;
  background:rgba(251,191,36,.07); border:1px solid rgba(251,191,36,.25);
  font-size:12px; color:#fbbf24; margin-bottom:16px; line-height:1.6;
}
</style>

<!-- Page header -->
<div style="margin-bottom:22px">
  <div style="font-size:22px;font-weight:800;font-family:'Sora',sans-serif">📦 Data Export & Import</div>
  <div style="font-size:13px;color:var(--text-muted);margin-top:3px">Backup your study data or restore it from a previous export</div>
</div>

<!-- Stats -->
<div class="dei-stats">
  <div class="dei-stat"><div class="dei-stat-n"><?= $counts['subjects'] ?></div><div class="dei-stat-l">Subjects</div></div>
  <div class="dei-stat"><div class="dei-stat-n"><?= $counts['sessions'] ?></div><div class="dei-stat-l">Sessions</div></div>
  <div class="dei-stat"><div class="dei-stat-n"><?= $counts['marks'] ?></div><div class="dei-stat-l">Marks</div></div>
  <div class="dei-stat"><div class="dei-stat-n"><?= $counts['tasks'] ?></div><div class="dei-stat-l">Tasks</div></div>
  <div class="dei-stat"><div class="dei-stat-n"><?= $counts['goals'] ?></div><div class="dei-stat-l">Goals</div></div>
</div>

<div class="dei-grid">

  <!-- ══ EXPORT ══ -->
  <div class="dei-card">
    <div class="dei-card-title">
      <svg width="18" height="18" fill="none" stroke="#818cf8" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
      Export Data
    </div>
    <div class="dei-card-sub">Download your data as JSON or CSV</div>

    <!-- Format -->
    <div style="font-size:12px;font-weight:700;color:var(--text-muted);margin-bottom:8px;text-transform:uppercase;letter-spacing:.5px">Format</div>
    <div class="format-row">
      <button class="fmt-btn active" data-fmt="json" onclick="setFmt(this,'json')">
        <div style="font-size:18px;margin-bottom:2px">{ }</div>JSON
        <div style="font-size:10px;opacity:.6;margin-top:2px">Re-importable</div>
      </button>
      <button class="fmt-btn" data-fmt="csv" onclick="setFmt(this,'csv')">
        <div style="font-size:18px;margin-bottom:2px">📊</div>CSV
        <div style="font-size:10px;opacity:.6;margin-top:2px">Excel / Sheets</div>
      </button>
    </div>

    <!-- What to export -->
    <div style="font-size:12px;font-weight:700;color:var(--text-muted);margin-bottom:8px;text-transform:uppercase;letter-spacing:.5px">What to export</div>
    <div class="exp-checks">
      <label class="exp-check-row checked" id="chk-all-row">
        <input type="checkbox" id="chk-all" checked onchange="toggleAll(this)">
        <span class="exp-check-icon">📦</span>
        <span class="exp-check-label"><strong>Full Backup</strong><span>All data below in one file</span></span>
      </label>
      <label class="exp-check-row checked" id="chk-subjects-row">
        <input type="checkbox" id="chk-subjects" checked onchange="syncAll()">
        <span class="exp-check-icon">📚</span>
        <span class="exp-check-label"><strong>Subjects & Marks</strong><span>Subject list + all exam scores</span></span>
        <span class="exp-check-count"><?= $counts['subjects'] ?> subj, <?= $counts['marks'] ?> marks</span>
      </label>
      <label class="exp-check-row checked" id="chk-sessions-row">
        <input type="checkbox" id="chk-sessions" checked onchange="syncAll()">
        <span class="exp-check-icon">⏱️</span>
        <span class="exp-check-label"><strong>Study Sessions</strong><span>Daily study logs</span></span>
        <span class="exp-check-count"><?= $counts['sessions'] ?> records</span>
      </label>
      <label class="exp-check-row checked" id="chk-tasks-row">
        <input type="checkbox" id="chk-tasks" checked onchange="syncAll()">
        <span class="exp-check-icon">✅</span>
        <span class="exp-check-label"><strong>Tasks</strong><span>All tasks and their status</span></span>
        <span class="exp-check-count"><?= $counts['tasks'] ?> tasks</span>
      </label>
      <label class="exp-check-row checked" id="chk-goals-row">
        <input type="checkbox" id="chk-goals" checked onchange="syncAll()">
        <span class="exp-check-icon">🎯</span>
        <span class="exp-check-label"><strong>Goals</strong><span>Study goals and progress</span></span>
        <span class="exp-check-count"><?= $counts['goals'] ?> goals</span>
      </label>
    </div>

    <button class="btn-export" onclick="doExport()">
      <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
      Download Export
    </button>
  </div>

  <!-- ══ IMPORT ══ -->
  <div class="dei-card">
    <div class="dei-card-title">
      <svg width="18" height="18" fill="none" stroke="#38bdf8" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
      Import Data
    </div>
    <div class="dei-card-sub">Restore from a StudyTrack JSON backup file</div>

    <!-- Import mode -->
    <div style="font-size:12px;font-weight:700;color:var(--text-muted);margin-bottom:8px;text-transform:uppercase;letter-spacing:.5px">Import Mode</div>
    <div class="mode-row">
      <button class="mode-btn active" data-mode="merge" onclick="setMode(this,'merge')">
        <div style="font-size:16px;margin-bottom:2px">🔀</div>
        Merge
        <div style="font-size:10px;opacity:.6;margin-top:2px">Add to existing data</div>
      </button>
      <button class="mode-btn" data-mode="replace" onclick="setMode(this,'replace')">
        <div style="font-size:16px;margin-bottom:2px">🔄</div>
        Replace
        <div style="font-size:10px;opacity:.6;margin-top:2px">Overwrite existing</div>
      </button>
    </div>

    <div class="dei-warn" id="replaceWarn" style="display:none">
      ⚠️ <span><strong>Replace mode</strong> will permanently delete your selected existing data before importing. This cannot be undone.</span>
    </div>

    <!-- What to import -->
    <div style="font-size:12px;font-weight:700;color:var(--text-muted);margin-bottom:8px;text-transform:uppercase;letter-spacing:.5px">Sections to import</div>
    <div class="exp-checks" style="margin-bottom:16px">
      <label class="exp-check-row checked" id="ichk-subjects-row">
        <input type="checkbox" id="ichk-subjects" checked onchange="updateRow(this,'ichk-subjects-row')">
        <span class="exp-check-icon">📚</span>
        <span class="exp-check-label"><strong>Subjects & Marks</strong></span>
      </label>
      <label class="exp-check-row checked" id="ichk-sessions-row">
        <input type="checkbox" id="ichk-sessions" checked onchange="updateRow(this,'ichk-sessions-row')">
        <span class="exp-check-icon">⏱️</span>
        <span class="exp-check-label"><strong>Study Sessions</strong></span>
      </label>
      <label class="exp-check-row checked" id="ichk-tasks-row">
        <input type="checkbox" id="ichk-tasks" checked onchange="updateRow(this,'ichk-tasks-row')">
        <span class="exp-check-icon">✅</span>
        <span class="exp-check-label"><strong>Tasks</strong></span>
      </label>
      <label class="exp-check-row checked" id="ichk-goals-row">
        <input type="checkbox" id="ichk-goals" checked onchange="updateRow(this,'ichk-goals-row')">
        <span class="exp-check-icon">🎯</span>
        <span class="exp-check-label"><strong>Goals</strong></span>
      </label>
    </div>

    <!-- Drop zone -->
    <div class="drop-zone" id="dropZone">
      <input type="file" id="importFile" accept=".json" onchange="fileChosen(this)">
      <div class="drop-icon">📂</div>
      <div class="drop-text">Drop your JSON backup here</div>
      <div class="drop-sub">or click to browse</div>
      <div class="drop-file-name" id="dropFileName"></div>
    </div>

    <!-- Preview meta -->
    <div id="importMeta" style="display:none;padding:10px 14px;border-radius:10px;background:rgba(14,165,233,.07);border:1px solid rgba(14,165,233,.2);font-size:12px;color:var(--text-muted);margin-bottom:12px;line-height:1.8">
    </div>

    <button class="btn-import" id="btnImport" onclick="doImport()" disabled>
      <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
      <span id="btnImportLabel">Select a file first</span>
    </button>

    <div class="dei-result" id="importResult"></div>
  </div>
</div>

<?php require_once 'includes/footer.php'; renderFooter(); ?>

<script>
/* ── Export state ── */
let expFormat = 'json';

function setFmt(btn, fmt) {
  document.querySelectorAll('.fmt-btn').forEach(b=>b.classList.remove('active'));
  btn.classList.add('active'); expFormat = fmt;
}

function toggleAll(cb) {
  ['chk-subjects','chk-sessions','chk-tasks','chk-goals'].forEach(id=>{
    const el = document.getElementById(id);
    el.checked = cb.checked;
    updateRow(el, id+'-row');
  });
}

function syncAll() {
  const all = ['chk-subjects','chk-sessions','chk-tasks','chk-goals'].every(id=>document.getElementById(id).checked);
  document.getElementById('chk-all').checked = all;
  updateRow(document.getElementById('chk-all'), 'chk-all-row');
  ['chk-subjects','chk-sessions','chk-tasks','chk-goals'].forEach(id=>
    updateRow(document.getElementById(id), id+'-row'));
}

function updateRow(cb, rowId) {
  const row = document.getElementById(rowId);
  if (row) row.classList.toggle('checked', cb.checked);
}

function doExport() {
  const all = document.getElementById('chk-all').checked;
  if (all) { window.location.href = `?export=all&format=${expFormat}`; return; }

  const parts = [];
  if (document.getElementById('chk-subjects').checked) parts.push('subjects');
  if (document.getElementById('chk-sessions').checked) parts.push('sessions');
  if (document.getElementById('chk-tasks').checked)    parts.push('tasks');
  if (document.getElementById('chk-goals').checked)    parts.push('goals');

  if (!parts.length) { alert('Please select at least one section to export.'); return; }

  // If only one section, use direct type
  if (parts.length === 1) {
    window.location.href = `?export=${parts[0]}&format=${expFormat}`;
  } else {
    // Multiple sections — export as "all" with JSON (CSV handles individually)
    window.location.href = `?export=all&format=${expFormat}`;
  }
}

/* ── Import state ── */
let impMode = 'merge';
let impFile = null;

function setMode(btn, mode) {
  document.querySelectorAll('.mode-btn').forEach(b=>b.classList.remove('active'));
  btn.classList.add('active'); impMode = mode;
  document.getElementById('replaceWarn').style.display = mode==='replace' ? 'flex' : 'none';
}

/* Drag & drop */
const dz = document.getElementById('dropZone');
dz.addEventListener('dragover', e=>{ e.preventDefault(); dz.classList.add('drag'); });
dz.addEventListener('dragleave', ()=>dz.classList.remove('drag'));
dz.addEventListener('drop', e=>{
  e.preventDefault(); dz.classList.remove('drag');
  const f = e.dataTransfer.files[0];
  if (f && f.name.endsWith('.json')) {
    document.getElementById('importFile').files; // can't set, handle manually
    handleFile(f);
  } else { alert('Please drop a .json file.'); }
});

function fileChosen(input) {
  if (input.files[0]) handleFile(input.files[0]);
}

function handleFile(file) {
  impFile = file;
  const nameEl = document.getElementById('dropFileName');
  nameEl.textContent = '📄 ' + file.name;
  nameEl.style.display = 'block';

  const reader = new FileReader();
  reader.onload = e => {
    try {
      const json = JSON.parse(e.target.result);
      if (!json._meta || !json.data) { alert('Invalid StudyTrack backup file.'); impFile=null; return; }
      const m = json._meta;
      const d = json.data;
      const counts = [];
      if (d.subjects)       counts.push(`📚 ${d.subjects.length} subjects`);
      if (d.study_sessions) counts.push(`⏱️ ${d.study_sessions.length} sessions`);
      if (d.tasks)          counts.push(`✅ ${d.tasks.length} tasks`);
      if (d.goals)          counts.push(`🎯 ${d.goals.length} goals`);
      document.getElementById('importMeta').style.display = 'block';
      document.getElementById('importMeta').innerHTML =
        `<strong style="color:var(--text-primary)">📦 ${m.app} Backup</strong><br>
         Exported: ${m.exported_at} &nbsp;|&nbsp; By: ${m.exported_by || '—'}<br>
         Contains: ${counts.join(', ')}`;
      document.getElementById('btnImport').disabled = false;
      document.getElementById('btnImportLabel').textContent = 'Start Import';
    } catch(err) { alert('Could not read file. Make sure it is a valid StudyTrack JSON backup.'); impFile=null; }
  };
  reader.readAsText(file);
}

async function doImport() {
  if (!impFile) return;

  const sections = [];
  if (document.getElementById('ichk-subjects').checked) sections.push('subjects');
  if (document.getElementById('ichk-sessions').checked) sections.push('sessions');
  if (document.getElementById('ichk-tasks').checked)    sections.push('tasks');
  if (document.getElementById('ichk-goals').checked)    sections.push('goals');
  if (!sections.length) { alert('Select at least one section to import.'); return; }

  if (impMode === 'replace' && !(await stConfirm('Replace mode will DELETE your existing data for the selected sections. Are you sure?'))) return;

  const btn = document.getElementById('btnImport');
  btn.disabled = true;
  document.getElementById('btnImportLabel').textContent = 'Importing…';

  const fd = new FormData();
  fd.append('action', 'import');
  fd.append('import_file', impFile);
  fd.append('mode', impMode);
  fd.append('sections', JSON.stringify(sections));

  try {
    const res = await fetch(location.href, {
      method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd
    });
    const data = await res.json();
    const result = document.getElementById('importResult');
    result.style.display = 'block';

    if (data.success) {
      const s = data.stats;
      result.className = 'dei-result success';
      result.innerHTML = `
        <div class="dei-result-title">✅ Import Successful!</div>
        <div style="font-size:12px;opacity:.8;margin-bottom:8px">Data has been added to your account.</div>
        <div class="dei-result-stat-row">
          <div class="dei-result-stat"><strong>${s.subjects}</strong><span>Subjects</span></div>
          <div class="dei-result-stat"><strong>${s.marks}</strong><span>Marks</span></div>
          <div class="dei-result-stat"><strong>${s.sessions}</strong><span>Sessions</span></div>
          <div class="dei-result-stat"><strong>${s.tasks}</strong><span>Tasks</span></div>
          <div class="dei-result-stat"><strong>${s.goals}</strong><span>Goals</span></div>
          <div class="dei-result-stat"><strong>${s.skipped}</strong><span>Skipped</span></div>
        </div>`;
      setTimeout(()=>location.reload(), 2500);
    } else {
      result.className = 'dei-result error';
      result.innerHTML = `<div class="dei-result-title">❌ Import Failed</div>${data.message||'Unknown error.'}`;
      btn.disabled = false;
      document.getElementById('btnImportLabel').textContent = 'Try Again';
    }
  } catch(err) {
    document.getElementById('importResult').className = 'dei-result error';
    document.getElementById('importResult').style.display = 'block';
    document.getElementById('importResult').textContent = 'Network error. Please try again.';
    btn.disabled = false;
    document.getElementById('btnImportLabel').textContent = 'Try Again';
  }
}
</script>