#!/usr/bin/perl
use warnings;
use strict;
use autodie;

use DBI;

my $pn2name;
open(my $n, '<', 'subvision-numbers.txt');
while(<$n>) {
	chomp;
	my ( $number, $pn, $imei, $name ) = split(/ /,$_);
	$pn2name->{$pn} = $number;
}

my $dbh = DBI->connect("dbi:Pg:dbname=zc","dpavlin","", { RaiseError => 1 });
my $sth = $dbh->prepare( "select * from sub_bakaceva" );
$sth->execute;

my $yyyy_mm;
my $out;

while( my $row = $sth->fetchrow_arrayref ) {
	my $ym = $row->[0];
	$ym =~ s{(\d\d\d\d-\d\d).*}{$1};
	my $pn = $row->[-1];
	my $name = $pn2name->{$pn} || die "no name for $pn";

	if ( ! defined( $out->{$name}->{$ym} ) ) {
		my $filename = "www/export/$ym-$name.csv";
		warn "# $filename\n";
		open( $out->{$name}->{$ym}, '>', $filename );
		print {$out->{$name}->{$ym}} join(',', @{ $sth->{NAME} }) . "\n";
	}

	print {$out->{$name}->{$ym}} join(',',@$row) . "\n";
}
